Tuesday, April 28, 2009

Doing page redirection in PHP



Page redirection can be done in PHP file using header() which is used to send a raw HTTP header.

(i-e) header("Location:newpage.php"); will load the newpage.php.

Note that header() must be used before sending any output either by HTML tags, blank lines or from PHP. Otherwise error message "header already sent" will be shown.

In this situation, we can use javascript for doing page redirection as below

window.location="newpage.php";

Some users might have disabled javascript in this browser for security reasons.
In this case, we can show a link for them go to the desired page.

Find below function written in PHP for doing page redirection by handling all the scenarios.

function redirect()
{

if (!headers_sent()) header("Location:newpage.php");
else echo "<script>window.location=\"newpage.php\";</script>
<noscript>Automatic redirection didn't work.<br />
<a href=\"newpage.php\">Click here to go to newpage.</a></noscript>";
}



If you want to use the variables of current page in the new page also, then include the new page (e.g include "newpage.php";)instead of doing redirection.

More Articles...

No comments:



Thanks for visiting our blog


twitterrss facebook linkedin YouTube subscribe


Subscribe via email

Enter your email address: