I'm new to PHP and am wondering how to handle redirection in case of error.
I have a script which calls a function:
$cart_object->Go2Server();
$echo 'error';
Now, if all goes well the script will redirect the user to another url. However, if something goes wrong the page refreshes and i see the error message. Ie, the function returns.
What I'm not sure of is how to redirect the user somewhere else if the function returns. If i have the following, the redirect_to_error is sometimes called when there is no error.
$cart_object->Go2Server();
redirect_to_error();
EDIT - sorry I should add, if the script dies after the redirect, how can it return a value?
The header function can take care of this
http://php.net/manual/en/function.header.php
Example :
header("Location: http://www.google.com");
exit;
You'll need to return a bool value from the function and check the value with an if statement in order to redirect to a specific page.
In your Go2Server function, consider having it return a boolean variable that indicates whether or not the headers have been set correctly to redirect the user. That is, if Go2Server works, return true, otherwise return false.
Then, run your redirect_to_error function if the boolean is false. To redirect someone, use the header function. e.g.
header('Location: www.example.com');
Is the redirect taken place in the $cart_object->Go2Server(); function?
If so is there an exit() or die() after the redirect?
The script continues when doing a redirect that's why you always need to end the script execution after redirect.
It would have been helpful if you'd shown the HTTP headers for successful and failed operations.
It sounds like you may be trying to issue a HTTP redirect (i.e. a 302 response code) after the page output has started (at which point the headers cannot be changed). If you've got your error reporting set up correctly you should see lots of 'headers sent' in your logs.
Related
The redirect() helper function in the helper file does not work in Laravel.
Here is my code helpers.php
if (! function_exists('license_check')) {
function license_check(){
//This does not work, returns a blank page
return redirect()->route('loginlicense');
//This does not work, returns a blank page
return \Redirect::route('loginlicense');
//This work but it prints on the browser before redirecting
echo \Redirect::route('loginlicense');
echo redirect()->route('loginlicense');
//This work but it prints on the browser before redirecting
die(\Redirect::route('loginlicense'));
die(redirect()->route('loginlicense'));
//The below works. But I would like to pass laravel flash sessions with `Laravel's with('status', 'My mesage')`
$url = route('loginlicense');
header("Location: ".$url);
exit();
}
}
license_check();
Why am I getting a blank page instead of being redirected to the url specified while using Redirect:: or redirect().
Same Issue
I had this issue - and did not want every controller action to worry about what this helper could deal with, so I figured that "Needs to be returned to the browser" could be accomplished by an echo and exit;
My Solution
// Redirect to the login?
if (empty($admin) || empty($token)) {
// I have to echo the redirect in order to return the response from here.
echo redirect('/admin/login');
exit;
}
More Explanation
Redirect - set headers only, before output.
When you redirect in PHP, you are only setting headers - that's what the redirect() function will do. This function derives to a Redirect Facade method to(), which returns a laravel RedirectResponse. When "echoing" it should only give back a response with headers and no body.
This means you cannot start outputting before the redirect. Remove any var_dumps, included template/view files, or other echos! Even a blank string or line space in a template file can ruin this.
Remember, you are server-side!
You would not be able to (due to errors - see headers already sent), or want to, redirect in the middle of a template file, because PHP is the language that is processed on the server side - so just once... if you need to be redirecting within a rendered view (probably based on some condition), use javascript!
More about "echo"
Because we are doing an echo redirect(), you may be scared of what the echo means. It is just sending back the full response (with only headers if done right!)
Sometimes I think that it is harder for people to realize that the only way PHP can ever send back a response (headers and the body) is through an echo (or similar outputting functions eg. printf, var_dump, etc), but most frameworks do not make you aware of this, so your only experience with echo is inside of templates.
Ps. Some frameworks utilize output_buffering to store the "echo" results in a buffer for last minute processing before sending everything.
Test it in your network tab of your browser
If you are doing it right, in the network tab of the browser, you will see a status code of 302 and the response section will say "Failed to load a response..." because it was redirecting.
If you are seeing the URL or anything else in the response tab, eg. the url , it is likely because you are sending out content via a var_dump, including a template file, or another echo that is creating a response body. Try using your browser network tab and preserve the log to see what is happening.
Even sending an empty string or line break counts as a response body (hence blank page). Typically you should get warnings about trying to set headers after some of the response body has already been sent in PHP. Basically, you should not be including a template or echoing anything out before a redirect. Your logic should process the redirect first thing!
The exit is there to make sure it does not go on to include your view or echo more things out!
It's because invoking redirect() by calling it inside a function does not work. Just like what Quezler said, it needs to be returned to the browser.
You can handle redirect in the controller. Helper function return a boolean value, or maybe throw exceptions.
helper.php
if (! function_exists('license_check')) {
function license_check($id) {
if($id == 2){
return true;
} else {
return false;
}
}
}
HomeController.php
use Session;
$check_lic = license_check(2);
if($check_lic) {
session()->flash('success', 'Your message!');
return redirect()->route('loginlicense');
} else {
session()->flash('error', 'you have not purchase licence!');
return redirect()->back();
}
I'm using a redirect function to redirect visitors to a certain page when they don't have access to the current page. The function is as follows:
$user->redirect('www.google.com');
die();
The redirect function links to:
public function redirect($url="",$time=0) {
header("Refresh: $time; url=$url");
}
Whenever you get redirected you briefly see a white page followed by the page you get redirected to. I'm assuming the white page is caused by die().
I don't like it and I really want to get rid of this.
The problem is not related to the die() call, but that you are sending the wrong header to handle a redirection.
Instad of doing
public function redirect($url="",$time=0) {
header("Refresh: $time; url=$url");
}
do:
public function redirect($url) {
header("Location: $url", true);
}
Or even:
public function redirect($url, $temporal = false) {
header("Location: $url", true, $temporal ? 302 : 301);
}
With this you are sending a status code "301" or "302", to indicate that the redirection is either temporal, or a permanent. Defaulting to a permanent redirect, since temporals are very rarely useful (although in your case, being a redirection because of permissions, a temporary redirection might be in order)
(I also removed the default value for $url, because it doesn't make much sense to redirect to an empty url)
Instead of using a 'Refresh:' header, you can just use 'Location:'. This way, the page does not have to be refreshed and will probably result in your desired behaviour.
public function redirect($url="/") {
header("Location: $url");
}
edit: added default $url '/' so that if no url was given it redirects to homepage
I'm disapointed to the prev. posts. It is about the die() !
When sending a header the browser takes a little time to take action. Between this time the php process then calls die() before you are redirected. This is asyc. Location and Redirect
So it shows you a black page and then you/visitors get redirected.
Good: setting die() to end the process to avoid futher actions inside your program
Bad: The blank page first.
This is depending on your enviroment of your browser! E.g: a very slow workstation will show you this behavior and you have to care about. Imagin the browser does know about header redirections (Today it (mostly) doesnt exists anymore)
To give the browser a change to take action, use this:
function someaction() {
// ...
$user->redirect('www.google.com');
// which give the time for the browser
// without further execution of your code
return;
}
In this case the visitor stays as long on the current page until the browser knows about headers or the cpu is slow but will take action when it is able to take action.
Here I have written that if...else condition with different header location.
$a = "yahoo";
if($a == "yahoo")
{
header('location:http://www.yahoo.com');
}else{
header('location:http://www.gmail.com');
}
header('location:http://www.google.com');
Problem:
In above code if condition is true then also it will redirecting to google.com
As per my opinion I think its first goes into if condition and then redirect to given location and other below code will not executed.
When I will write exit() or die() with every header It will work.
Question
Can anyone suggest me where its create issue?
Why without exit() or die() its not working?
The "Location:" header. Not only does it send this header back to the browser, but it also returns a REDIRECT (302) status code to the browser unless the 201 or a 3xx status code has already been set.
<?php
header("Location: http://www.example.com/"); /* Redirect browser */
/* Make sure that code below does not get executed when we redirect. */
exit;
?>
You can read more about this at the php manual php header
as you can find in this comment on docs: http://php.net/manual/en/function.header.php#85254
Headers are overwriten by themselfs. Therefore if you do not stop executing your code, your header is changed to 'google' and after that sent to the user..
I'm making a website that does a lot of PHP redirects depending on different scenarios.. Like so...
header("Location: somesite.com/redirectedpage.php");
I'm just trying to get a firm understanding of how the redirect works, for securities sake.
My question is, does PHP continue to execute after this header call?
For example... Would the echo still get executed in this bit of code?
function Redirect($URL)
{
header("Location: " . $URL);
}
Redirect("http://somesite.com/redirectedpage.php");
echo("Code still executed");
If so... Would me changing the Redirect function to this... make it the echo not execute but still redirect?
function Redirect($URL)
{
header("Location: " . $URL);
exit(1);
}
Redirect("http://somesite.com/redirectedpage.php");
echo("Code still executed");
I'm just trying to get a firm understanding of how the redirect works, for securities sake.
All the header() statement does is modify the headers your webserver (Apache, nginx, etc.) send to your browser. You've added a Location: header to the page, which tells the browser to redirect to that page. Everything else in the PHP script will execute, including your echo, but you probably won't see it because you are going to be redirected to a new location.
The header command doesn't interrupt the flow of your code. Even if that is encountered, your page is still downloaded by the browser, even if it isn't show. Consider 404 pages, which (despite being errors) are still processed by the browser (though they are rendered while redirects are not).
You can output a lot more headers than just Location headers with header, most of which you don't want to stop your code execution. If you want to stop code execution, you need to call exit explicitly.
For example, here:
<?php
session_start();
if (!isset($_SESSION['is_logged_in'])) {
header("Location: login.php");
die();
}
?>
<Some HTML content>
Is die() really necessary here ?
Is die() really necessary here ?
It is: Otherwise, the client will still get the HTML code in the response body. The header asks the client to terminate and go to the new page, but it can't force it.
The client can always continue listening to the response, and receive everything output afterwards, which is a fatal security hole e.g. when protecting sensitive data in a login area.
Yes, die() is necessary. A call to header("Location: some-location.php") sends the specified header (a 302 redirect in this case) to the browser; but it DOES NOT terminate the script. It becomes more important if the lines after the redirect statement contains PHP code which may execute unintentionally. So if want to send the redirect header and abort any further processing you must call die, exit, return or any other similar construct.
Note that it is possible to perform further processing after sending the redirect header.
Yes. Simply generating a header, even the Location header, does not terminate the current script. The HTML output will be visible in e.g. a packet sniffer.
I found that: http://www.figured-it-out.com/figured-out.php?sid=181
So according to this it seems that some browsers just stop receiving the html content and redirect directly to the new page where other browsers like IE still wait untill the loading of the page is ready.