Send 404 Header with php, when header already sent (workaround) - header

i have tried to send the 404 header with:
header('HTTP/1.0 404 Not Found');
but it doesn't work.
I think it doesn't work, because the header is sent at the end of the page.
Problem is...
if user request the page mydomain/help
--> Server shows help
if user verifies the email adresse with mydomain/blub#asdfsi.com
--> server activates the email adress
that means, the decision, if any page can be displayed or not, can only be given at the end of the page, because the possible URIs are not static...
has anyone an idea, how i can send the 404 header after processing / outputting many stuff?
PS: sorry for my bad english ;-)

Solution (at the beginning):
$allowed= array('Start' , 'Main', 'Sub' , 'Presub');
if (!in_array($url, $allowed))
{
header('HTTP/1.0 404 Not Found');
}
It works, but in the future, the array could be long and longer and longer...
Any other ideas?

If you have this error, replace the header(Location: ...) by following:
echo '<script type="text/javascript">
window.location.href = "PATH TO REDIRECT TO";
</script>';

Related

Twilio mobile number verification - VerificationCheck was not found on Express

The requested resource /Services/serviceSSID/VerificationCheck was not found is the eroor showing in the console
my code is
otpLogin:async (req,res)=>{
console.log(req.body.otp);
try {
const isOTP = await client.verify.services(serviceSSID).verificationChecks.create({
to:`+91${req.body.phone}`,
code:req.body.otp
})
if(isOTP)console.log(isOTP);
return res.status(200).json({message:" mobile number verified"})
} catch (error) {
console.log(error.message)
return res.status(500).json({message:"something went wrong"})
}
}
Twilio developer evangelist here.
From the documentation:
Twilio deletes the verification SID once it’s:
expired (10 minutes)
approved
when the max attempts to check a code have been reached
If any of these occur, verification checks will return a 404 not found error like this:
Unable to create record: The requested resource /Services/VAXXXXXXXXXXXXX/VerificationCheck was not found
If you’d like to double check what happened with a given verification - please use the logs found in the Twilio Console under your Verification Service:
I've found that if you submit a form twice by clicking a submit button twice quickly, that the verification is successfully checked and then because it was a success deleted, then the second check fails with a 404 like this and that is the error result you see. To avoid this, you should stop users from being able to submit the form twice by disabling the submit button after the first attempt.
I can confirm that philnash 2nd statement is correct. However wouldn't it have been handled way better if instead we just get a response from client.verify.services(serviceSSID).verificationChecks that the 2nd (and so on checks) failed??

Getting the main url on which error occured in Yii 1

We have implemented an error handler for Yii 1. Also we have implemented the mail functionality with this as any error occurred an email will be send to us but the problem is we are not getting the current URL on which error is generating. Like one page controller/action can contain many images favicons etc. So if any image is missing then we are getting the image URL which showing 404 from:
$url = Yii::app()->createAbsoluteUrl(Yii::app()->request->url);
But we are not getting current URL not even in $error = Yii::app()->errorHandler->error.
So we are not getting the page in which image is absent. Please let me know if is there any way to get current page URL as I have tried many ways but all they are returning the missing images URL instead of main page URL for which images are missing.
createAbsoluteUrl() expects route as first argument - it may return random results if you provide URL instead of route (like in your code snippet).
If you want absolute URL of current request, you may use combination of getUrl() and getHostInfo():
$url = Yii::app()->request->getHostInfo() . Yii::app()->request->getUrl();
In case of error you can get current page url using Yii::app()->request->requestUri in Yii 1.

Difference between UseStatusCodePagesWithRedirects and UseStatusCodePagesWithReExecute - Status Code Pages in Asp.net core

I am using UseStatusCodePages Middleware to show status code pages on my application but it shows plain text on UI without any other information,
I want to show UI with Status Code Information along with some other helpful information like Customer Support Number with more user-friendly page.
I found out we can use two extension methods to do that which is UseStatusCodePagesWithRedirects and UseStatusCodePagesWithReExecute. Only Difference I found out from Microsoft Docs is,
UseStatusCodePagesWithRedirects : Send 302 to Client.
UseStatusCodePagesWithReExecute : Send Original Status Code and Executes handler for redirect URL.
Is that the only difference?
I think that the main difference is that UseStatusCodePagesWithRedirects is redirecting you to error controller action method while UseStatusCodePagesWithReExecute is just rendering page with out redirecting
Example
Controller actions
[Route("error/404")]
public IActionResult Error404(int code)
{
return View("Error404");
}
[Route("error/{code}")]
public IActionResult Error(int code)
{
return StatusCode(code);
}
Startup Cinfigue
app.UseStatusCodePagesWithRedirects("/error/{0}");
or
app.UseStatusCodePagesWithReExecute("/error/{0}");
Case 1 (404 Error)
Url : https://localhost:5001/notexits_page
1) UseStatusCodePagesWithRedirects
Result:
Url is: https://localhost:5001/error/404
We see Error404 page
2) UseStatusCodePagesWithReExecute
Result:
Url is: https://localhost:5001/notexits_page
We see Error404 page
Case2 (401 Error)
Url : https://localhost:5001/admin/users
1) UseStatusCodePagesWithRedirects
Result:
Url is: https://localhost:5001/error/401
We stack in infinity loop
1) UseStatusCodePagesWithRedirects
Result:
Url is: https://localhost:5001/admin/users
We see default browser error page for 401 error
When Using app.UseStatusCodePagesWithRedirects("/Error/{0}") and invalid request(lets say "/abc/xyz") is raised then;
Status Code 404 is issued, app.UseStatusCodePagesWithRedirects("/Error/{0}") intercepts the request and 302 status code is issued(which means URI of the requested resource has been changed temporarily)
As 302 is issued another get request is issued which results in change of the url from
"/abc/xyz" to "/Error/404".
As the request is redirected to the specific error controller the status code for the request is 200 ok in the browser developer tool.
But When Using app.UseStatusCodePagesWithReExecute("/Error/{0}") and invalid request(lets say "/abc/xyz") is raised then;
app.UseStatusCodePagesWithReExecute("/Error/{0}") middleware intercepts the 404 status code and re-executes the pipeline pointing it to the URL
As the middleware is re executing the pipeline the original URL "/abc/xyz" in the address bar is preserved. It does not change from "/abc/xyz" to "/Error/{0}".
Also the original status Code(404 in this case) is preserved in the developer tool.

API: Custom 404 not found error response structure

Considering this url: http://example.com/users/1/post/2/likes.
How can I correctly define structure of my 404 response, showing which item is not found? user, post or likes?
You can send an HTTP status code using the header() function, by starting the header with the status code number, followed by the message to send to the user.
header("404 " + $message);
The code that processes the parameters can determine which item isn't found, and put that into $message.

Cannot modify header information - headers already sent by (output [duplicate]

This question already has answers here:
How to fix "Headers already sent" error in PHP
(11 answers)
Closed 8 years ago.
I think I screwed up my website, this is an error I get on one of the pages
Warning : Cannot modify header information - headers already sent by (output started at /home/content/94/9066***/html/websites/{website name}.com/index.php:3) in /home/content/94/9066***/html/websites/{website name}.com/wp-includes/pluggable.php on line 896
How do I get rid of this? Thank you so much for your help!!
You get this error because you're setting a header (most likely with the header function) after some output (body) have already been sent to the client, for example with a echo
The line of code + source file where the body output starts and where you attemp to set a header are in the error you receive.
The rule is first all headers are set then comes the body of the response.
Or just because a line end... Check
<?php // is there a blank line before this one?
...
?> //same question
Usually this warning is thrown when an output (even a space or a blank line) is sent to the browser before the session function call.
As this is happening on a wordpress site, did you modify any code in index.php?
Check if anything is echoed before the session_start() function call.
If we have a little knowledge about HTTP headers, we can fix "Headers already sent" errors. So I will touch just the overview of headers.
During a HTTP request, HTTP headers called [REQUEST HEADERS] are sent from client to the server and during a HTTP response, HTTP headers called [RESPONSE HEADERS] are sent from server to client.
Now, what the hell these headers contain?
REQUEST HEADERS--> Hostname,cookie info, the kind of encoding that the client accepts,etc.
RESPONSE HEADERS--> Content type being sent, info about Content encoding, etc.
You can get a lot of info about the headers in the below link:
http://code.tutsplus.com/tutorials/http-headers-for-dummies--net-8039
In plain English, Headers contain information about the page being requested or sent.
Now Answering the ques:
Php header() function modifies the default RESPONSE headers and includes information that you want to send.
THUMBRULE:
Since response headers contain info about the page being sent to client,
RESPONSE headers should be sent **FIRST** before the page itself.
So when you echo or display something to the browser and then use the header() function,
<?php
echo "hi";
header("As you have already displayed "hi", this info will not be sent.);
?>
In the above code we have actually sent the page and then trying to send our header info,
so the headers will not be modified as the default headers were already sent and hence the error:
"Headers already sent".
Ans:
1) So, always include the header() function before displaying anything to the browser.
2)Another method to avoid the error is to use ob_start() function. This function just stores all the information that needs to be sent to the browser in a buffer memory, and it will output all at once.
Lets take a look at the code which will make more sense:
<?php
ob_start();
echo "hi";
echo "Hello"
header("This info will be sent");
ob_end_flush();
?>
In the above code, header info will be sent as both the echo statements will be stored in a buffer and will not be sent to the browser until the line ob_end_flush(); is executed. ob_end_flush() will just flush out the buffer memory sending all the info to the browser.
NOTE: But again make sure, you use the **ob_start()** function in the beginning.