PDA

View Full Version : [FAQ] How do I redirect users? (Location Header)



mdshare
04-06-2008, 07:49 PM
In PHP you can redirect a user to another page using the header() function.




<?php
header('Location: http://www.cegamerspace.com);
?>

http://www.php.net/header

This function is used to modify the HTTP response headers sent out from the server. For this example the 'Location' header is modified, the browser then picks up on the modification and makes a new request from the new location specified.

Because this function modifies the HTTP headers, it may not be included after output has started from the script.

For example:



<?php
echo 'Hello, world!';
header('Location: http://www.cegamerspace.com);
?>



This throws a warning-level error saying something to the effect of headers cannot be modified, output already started at line x in file z.

This, on the other hand, is valid because it uses output control functions to buffer script output.


<?php

ob_start();

echo 'Hello, world!';
header('Location: http://www.cegamerspace.com');

ob_end_flush();

?>


Output from the script is written to the buffer, therefore, when the script reaches header() it is able to make HTTP header changes since nothing has yet been sent to the browser.

Output buffering increases resource consumption slightly because extra memory has to be allocated for the buffer.

More on output buffering:
http://www.php.net/outcontrol

Also, as a side note, it doesn't make any sense to have need of outputting anything before redirecting a user with the 'Location' header since all output will be lost anyway. However, this does come in handy for other functions or header modifications such as session_start() or setcookie() both of which make modifications to the outgoing HTTP headers. If you find you're in need of showing the user output before redirection, this is better done on the client-side with JavaScript.

Haunted Dawg
04-07-2008, 12:44 AM
Or you can use a php refresh method:



header("refresh 3; url='index.php'");
echo 'You are going to be redirected to index.php in 3 seconds.';

mdshare
04-07-2008, 02:03 AM
yep that works also, thx killah

but don't you have the text parsed first before the refresh ? didn't test it so no clue



<?php
echo "<p align=\"center\"> User Not Found</p>

"; // err msg
header('Refresh: 3; url=index.html'); // waits 3 seconds & sends to homepage
?>

Explaination:
1. Use of php to set up a simple html message as to what is happening
2. with header, there is a command, "Refresh" and here is how it works:
a. 'Refresh: 3; -- start all header commands with a single quote
b. Refresh requires a parameter that is in seconds which tells the browser
to refresh after this time period has passed.
c. The ; is necessary to separate it from the rest of the Refresh parameters
d. Refresh must be uppercased
3. After the ; put the url= command and put in your desired web page
4. Location doesn't work! with in this context.
5. Order matters. Refresh first, then it's second parameter, url=

Haunted Dawg
04-07-2008, 02:41 AM
yep that works also, thx killah

but don't you have the text parsed first before the refresh ? didn't test it so no clue



<?php
echo "<p align="center"> User Not Found</p>

"; // err msg
header('Refresh: 3; url=index.html'); // waits 3 seconds & sends to homepage
?>

Explaination:
1. Use of php to set up a simple html message as to what is happening
2. with header, there is a command, "Refresh" and here is how it works:
a. 'Refresh: 3; -- start all header commands with a single quote
b. Refresh requires a parameter that is in seconds which tells the browser
to refresh after this time period has passed.
c. The ; is necessary to separate it from the rest of the Refresh parameters
d. Refresh must be uppercased
3. After the ; put the url= command and put in your desired web page
4. Location doesn't work! with in this context.
5. Order matters. Refresh first, then it's second parameter, url=


You might be wrong there.

Ive tried it the other way arround and unfortunatly it does not work for me. If i put the header() at the bottom of the text it says Warning: headers already sent.

So i might be wrong or its just the normal php xD

You are right that is is
header('Refresh: 3; url=index.html'); the refresh MUST be uppercased. I was just proving a nice point of what you can do with a header() function.

Floydian
04-07-2008, 04:15 AM
Another method that I use for redirects sidesteps the whole issue of output. There is javascript code that can accomplish this. Of course, it requires that the user have javascript enabled (which if they don't, they're basically surfing the internet like the Flintstones).


// Redirect to new pages using javascript
function redirect($webpage){
echo <<<EOT
<script language="javascript" type="text/javascript">
<!--
window.location.replace("$webpage");
// -->
</script>
EOT;
exit();
}

This function is nice because you can use it anywhere without worrying about if anything has been output yet.
Using the .replace method replaces the web page you just left with the web page you are redirected to in the browser history.

This has the effect of allowing the user to use the back button to go back to the page right before the page they were redirected from.

Here's a lil illustration of the concept:

Example One -- Without .replace
You're on Page A
You click a link taking you to Page B
Page B redirects you to Page C

Normally a redirect put pages into your history like this:

Page C
Page B
Page A

In descending order starting with the last page accessed.
Hitting the back button when on Page C, takes you back to Page B which then attempts to redirect you back to Page C.

Example Two -- With .replace
You're on Page A
You click a link taking you to Page B
Page B redirects you to Page C

Your browser history now looks like this:

Page C
Page A

Now, if you hit the back button, you aren't taken to Page B which attempts to redirect you back to Page C, but you go to Page A which is what would be the expected behavior.

I don't know if the header redirect does example One or Two, but I mention this in case you go with the javascript approach. The default location.window(URL) behavior is that of Example One, so I want to make sure people that go with the javascript approach know the difference.

Of course none of this is to say that the header approach isn't good. This is simply a different flavor of coding that some of you may like since you can call it with a simple function: redirect('URL'); without any further thought required. ;)

Please note that if you use Databased Sessions (if you don't know, then you are NOT using databased sessions, just trust me on that) then before you do a redirect, you must call the session_write_close() function to force the session to be written to the database or else you're going to get a slew of errors (about 8 if I counted right). Of course, the number of errors I encounter in that situation is probably dependent on how my custom session handler functions are written lol.

mdshare
04-07-2008, 04:26 AM
Using the header you just don't have the back button anymore , no history by using header(

Now we could also use the meta refresh (back button is available again) but sadly enough firefox has issues with correct execution of the meta refresh.


@session_write_close();
if (!headers_sent($file, $line))
{
@header("Location: $url");
echo "<meta HTTP-EQUIV="REFRESH" CONTENT="0; URL=$url">";
}
echo "
Headers already sent in {$file} on line {$line}";
echo "
Please click {$url} to continue...";
exit;

Floydian
04-07-2008, 05:11 AM
I did not know that, thanks for the info ;)

Zeggy
04-20-2008, 05:52 PM
Just a little footnote here:
Don't forget to exit(); after your redirects.

Haunted Dawg
04-20-2008, 06:42 PM
Yes i have noticed lately that using this code:



if($_SESSION['test'] != 1)
{
header("location: test_login.php");
}


Generates a Warning error.
But using this code:



if($_SESSION['test'] != 1)
{
header("location: test_login.php");
exit;
}


Gets rid of the warning error.

Zeggy
04-20-2008, 06:46 PM
Yep. It's probably because the code after the redirect is still being processed and sent to the browser.