PHP Redirect To Another Page

November 20, 2011 · 33 comments

by Lars

PHP Redirect To Another Page

With PHP it is possible to redirect to another page using the header() network function. The header() function is used to send a raw HTTP header why it can easily be used transfer a user to a new page without clicking on a link. If you are not familiar with the header() function you need to be aware that just like in any other web programming language it is required to write the headers before the actual page content is sent. So if you experience any errors keep in mind that it is a common error to read code with e.g. include() or require() functions and have spaces or empty lines that are output before header() is called. In this tutorial I will show you in detail how to use header() to perform redirects in PHP.


ElegantThemes
ThemeForest

Advertisement

PHP redirect to another page is in some cases useful and it is easy to do as well using one line of code. To do it right however I recommend you add and exit(); also to stop any execution of the rest of the page.

<?php

/* Remember header() must be called before any actual output is sent */
/* Redirect browser */
header("Location: http://www.tripwiremagazine.com/");

/* For good order don’t risk the code below the redirect
to be executed when we redirect. */
exit;
?>

In order to make it absolutely clear what is meant by “header() must be called before any actual output is sent” I have added an example that will not work.

<html>
<?php
/* The echo construct output text directly to the page */
echo "This is written to the page!!!";

/* Remember header() must be called before any actual output is sent
(normal HTML tags, blank lines in a file, or from PHP) */
header("Location: http://www.tripwiremagazine.com/");

exit;
?>

Both the <html> and the use of echo before the header redirect will make this code fail.

It is important to note that headers are actually sent when the first byte is output to the browser. If you are replacing headers in your scripts, this means that the placement of echo/print statements and output buffers may actually impact which headers are sent. In the case of redirects, if you forget to terminate your script after sending the header, adding a buffer or sending a character may change which page your users are sent to.

This redirects to 2.html since the second header replaces the first.

<?php
header("location: 1.html");
header("location: 2.html"); //replaces 1.html
?>

This redirects to 1.html since the header is sent as soon as the echo happens. You also won’t see any “headers already sent” errors because the browser follows the redirect before it can display the error.

<?php
header("location: 1.html");
echo "send data";
header("location: 2.html"); //1.html already sent
?>

Wrapping the previous example in an output buffer actually changes the behavior of the script! This is because headers aren’t sent until the output buffer is flushed.

<?php
ob_start();
header("location: 1.html");
echo "send data";
header("location: 2.html"); //replaces 1.html
ob_end_flush(); //now the headers are sent
?>

Please share your experience and thoughts on this “php redirect to another page” tutorial in a comment.

We like to showcase and inspire you with nice things like this  beautiful Epiphone Les Paul vintage Sunburst. Please have a look.

Thanks for visiting us. Do you have a Ebook reader? There is a lot of awesome Nook color covers that will personalize and protect your Nook color. You can also take a look at these stunning birthday cake pictures or these Justin Bieber pics and accessories

{ 30 comments… read them below or add one }

Renee Skolnick June 3, 2013 at 1:45 pm

is it possible to have an “if” function and if its true it redirects to that page.

like i’m sending text from a form to be $url
and i want that to show up in an iframe on the original page
so i want the php handeler to redirect to $url

Is this possible?

Reply

freakqnc June 4, 2013 at 6:33 am

Renee, it should be possible, have you tried putting some code together? Hard to tell without reading through the code. Best of luck with your project.

Reply

Jason May 10, 2013 at 6:50 pm

Hello :)

I am trying to get a html thank you page to load after my php is done taking in the information from a form, generating a pdf, and send that pdf via email. I pieced together the code and think ive done a decent job considering I know relatively little about php. I mean heck the thing runs so far right, I just cant get the Thank you for your Info page to load after the user hits submit. I tried the snippet above and it still just send the emal and downloads the pdf, but after just sits on the form. Any Ideas? I am sure yall might want to look at some code, just let me know what snippets you want and I will post them. Your help is greatly appreciated.

Reply

nawa May 1, 2013 at 9:26 am

Hello everyone is there a way i can add two redirects to one page?

Reply

Dave April 17, 2013 at 8:24 pm

Asif, Robert, & Ganish,
It is not working for you guys because you have information sent to the client before the header command. Asif & Ganish, in your cases it is, at the very least, the echo statement. Robert, I’m sure the header.html that you are including is sending something.

As Lars stated in the original article:
In order to make it absolutely clear what is meant by “header() must be called before any actual output is sent” I have added an example that will not work.
********

Both the and the use of echo before the header redirect will make this code fail.

Lars, thank you very much. This was very clear, concise, and specific and a great help to me.

Reply

Dave April 17, 2013 at 8:25 pm

Okay, Lars’ example didn’t paste into the reply, but it is the 2nd example in his article you should look at.

Reply

sagar April 3, 2013 at 7:06 pm

what should i do if I wanna redirect the page in the localhost itself (html->page->that html page) ????

Reply

Asif February 20, 2013 at 7:51 am

I am trying to log out user and echo some message but does not work. Any pointer?
thanks

<?php
session_start();
session_unset();
session_destroy();
// unset cookies by setting it to some neagative or past time
setcookie("username" , "" , time()-20);

function callback($buffer)
{
echo 'You have been signed out successfully! ‘;
}

ob_start(“callback”);

header(“Location: /index.php”);

ob_end_flush();

exit();
?>

Reply

tfbkny February 13, 2013 at 2:16 pm

I am no php dev but could it be the parentheses? My code has none and the include and redirect work fine my include looks like:
include $_SERVER['DOCUMENT_ROOT'].’/includes/header.html’;

Also I used a function call (in which there is a call to the header function) that I’ve placed in the file includes/site-functions.php

header(“Location:”.$_SERVER['HOST_NAME'].”/store2.php”);

I might completely off, I am just making a deduction on the fact that my code is somewhat similar and it’s working… I hope that helps you at least in troubleshooting :)

Reply

Robert Searing February 12, 2013 at 8:37 pm

I’m having some difficulty getting my shopping cart page to run properly and I know it’s because of my inexperience with headers and ob_start().

The way my site is set up is such that I have a header.html file that contains pretty much the static content of the site (ie nav bar, etc). Within that file, I have a session_start() and a ob_start() command and then I simply “include” the file into each individual page.

What I’m trying to do is redirect the shopping cart if a user removes items so that the count of items is 0. Thus – I have:

….
….
include($_SERVER['DOCUMENT_ROOT'].’/includes/header.html’);
$cart = new Cart();
$count = $cart->countItems();
if ($count==0) {
header(“Location: /store2.php”);
exit;
}
….
….
….
ob_end_flush();
?>

What’s ironic is the page will not redirect upon the count going to 0 – but will if I refresh on the empty shopping cart.

Any ideas why?

Thanks SO MUCH!
Rob Searing

Reply

tfbkny February 12, 2013 at 7:07 am

Thank you so much LARS!… Years later your post solved yet another problem that no stackoverflow repurposing had been capable to help solve. The explanation you gave was clear and to the point, it’s a shame that php.net documentation didn’t offer anything remotely comparable to solve the issues that header has been giving me and many others (judging from the numbers of results of people asking the same about the same problem related to use of header in PHP.

If only there were more concise and clear explanations like the one you posted above, I’d be already in far better shape by now, when it comes to programming! Thanks again! ;D

I might be saying an enormity, but since it gives so many problems, why not change its behavior to be buffered by default since it’s extremely likely it will be used to redirect pages after an output has occurred? The exception should perhaps be a non-buffered behavior then… might be an “ignorant” (as in not knowing) observation, but it’s my instinctive logic deduction seeing how a feature such as header(“location: mysite.com/myfile.php”); is being used most :)

Cheers!

Reply

Craig February 1, 2013 at 4:53 am

Yuvaraj

will it redirect to all x111 ids if say.. you had 10 x111′s or so..
or just the very last one?

Reply

Ganesh January 8, 2013 at 11:40 am

Can anybody help how to redirect a page in php if the certain ‘IF’ condition is true, i tried using a mysql_num_rows…

Reply

Yuvaraj January 31, 2013 at 6:36 am

for example in
$query=”select * from table1 where id=’x111′ “;
$res=mysql_query(query);
if(mysql_num_rows($res)>0)
{
echo “this query contain one result”;
header(“location:profile.php”);
}

Reply

Amit December 9, 2012 at 4:11 pm

How to redirect to a particular section of another php/html page? Section can identified by the class or id tag in html.

Reply

rahul soni December 1, 2012 at 2:13 pm

——————————————————
ob_start();
header(“location: 1.html”);
echo “send data”;
header(“location: 2.html”); //replaces 1.html
ob_end_flush(); //now the headers are sent

———————————————–

This is greate solutions……….thanx for it.

Reply

sajid November 2, 2012 at 5:36 pm

Thank you, you release my tension

Reply

smita September 22, 2012 at 8:50 am

Great informationnnn!!
thaq so much…

Reply

awan September 12, 2012 at 6:15 pm

i got stuck with session_destroy >,,<

=1) {
echo "";
exit;
}
}
if ($_GET['aksi']=="info") {
?>

Reply

Laura August 24, 2012 at 1:06 pm

Hello :)

Apologies if this sounds particularly dense owing to the simplicity of the task but…

My php complete with link to a new page is within an Iframe (on a Wix site). I’d like to get this link to open in the parent page. Currently the link opens but within the Iframe. Does anyone know how to do this?

Any help would be very much appreciated!

Reply

Dots n' Colors July 28, 2012 at 5:32 am

Thanks a lot, dude

Reply

Mandeep May 28, 2012 at 8:48 am

header(“Location:filename.php”); is not working.
I got an error
Cannot modify header information – headers already sent by (output started at D:\xampp\htdocs\xampp\InsertInformation.php:3) in D:\xampp\htdocs\xampp\InsertInformation.php on line 5
Please Help me
Thank you.

Reply

Gennady May 29, 2012 at 1:25 am

Mandeep, first of all, as I mentioned above, **ALWAYS** use absolute URLs, not just “filename.php” but “http://yoursite.com/filename.php”.

As for the modification error, you are outputting some data to the browser before sending the headers, your code may have some stray spaces, linefeeds before the opening tag, or a byte order marker (BOM) perhaps.

Reply

tfbkny February 12, 2013 at 7:20 am

By the way… thank you Mandeep for posting the error because in my case it was the query string “Cannot modify header information – headers already sent by” in google which allowed me to find this super helpful post that provided the solution to my problem after 2 days of searching the web! :D

Reply

Gennady March 3, 2012 at 9:42 am

Ah! Make sure to __ALWAYS__ exit() or die() after a location header and __ALWAYS__ use **ABSOLUTE** paths as location; there have been cases where undefined behavior (specifically under Windows) resulted in not sticking to these 2 very important rules.

Also worth mentioning is the the headers_list() function that retunrs an array of the currently set headers and the headers_sent() function to check whether headers have been sent or not.

Reply

suneel kumar March 1, 2012 at 10:00 am

i want a code in php redirect one page to another page

Reply

Rl435 January 22, 2012 at 4:50 pm

ob_start();
header(“location: 1.html”);
echo “send data”;
header(“location: 2.html”); //replaces 1.html
ob_end_flush(); //now the headers are sent

Thanks do much for this – I have been looking for a solution to this for a long time

Reply

john February 2, 2012 at 8:40 pm

great detailed info. I’ve been all day though and still can’t get redirect to work.
It always prints to the php web page. I went to me file manager and edited it from there, and it just prints the code to php webpage instead of reidrecting it. I tried ob and using exit to but nothing makes it redirect. I can only get meta redirect to work but not the location:
any ideas
I am naming my file login.php
thanks john

Reply

Lars February 2, 2012 at 11:39 pm

Make sure you edit and save your code in code / html mode (when editing online). Otherwise the special characters will be encoded and then the code will not be executed.

Reply

Gennady March 3, 2012 at 9:45 am

Sounds like you’re not running a PHP gateway or not directing requests through it properly, if you’re getting the PHP code rendered instead of interpreted. What webserver are you using nginx, Apache, lighttpd, other? What PHP SAPI are you using FPM?

Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

{ 3 trackbacks }

Previous post:

Next post:


Web Analytics