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.
[exec]$filestr = file_get_contents (‘http://www.tripwiremagazine.com/googleadsensebelowmoretag.inc’);echo $filestr;[/exec]
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
Lars started tripwire magazine back in January 2009. He is really passionate about web design, web development and loves to look into new technologies, techniques, tools etc. and to write articles for his readers.
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?
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.
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… Read more »
Hello everyone is there a way i can add two redirects to one page?
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… Read more »
Okay, Lars’ example didn’t paste into the reply, but it is the 2nd example in his article you should look at.
what should i do if I wanna redirect the page in the localhost itself (html->page->that html page) ????
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();
?>
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 🙂
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 –… Read more »
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… Read more »
Yuvaraj
will it redirect to all x111 ids if say.. you had 10 x111’s or so..
or just the very last one?
Can anybody help how to redirect a page in php if the certain ‘IF’ condition is true, i tried using a mysql_num_rows…
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”);
}
How to redirect to a particular section of another php/html page? Section can identified by the class or id tag in html.
——————————————————
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.
Thank you, you release my tension
Great informationnnn!!
thaq so much…
i got stuck with session_destroy >,,<
=1) {
echo "";
exit;
}
}
if ($_GET['aksi']=="info") {
?>
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!
Thanks a lot, dude
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.
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.
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! 😀
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.
i want a code in php redirect one page to another page
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
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
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.
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?
[…] PHP Redirect To Another Page. W ramach zgodno?ci z tytu?em: ABC PHP, czyli artyku? o przekierowaniach na inny adres URL. […]
[…] je vous invite donc à découvrir l’article que je vous ai mit en lien ci-dessous : PHP Redirect To Another PageYahoo et LinuxIci un petit article qui nous informe que Yahoo rejoint la fondation Linux. Une bonne […]
[…] original here: PHP Redirect To Another Page – tripwire magazine Share and […]