Redirect PHP script in pages & types of redirect

Redirecting a visitor or the browser is required in different situations. If a a page is temporarely down then we can use HTTP 302 redirect. Same way permanent redirection is HTTP 301 redirection. All the 3xx are different types of redirection and out of them 301 and 302 are common.
Temporary / Permanent Cacheable Request Method Subsequent Request
301 Permanent yes GET / POST may change
302 Temporary not by default GET / POST may change
303 Temporary never always GET
307 Temporary not by default may not change
308 Permanent by default may not change
We will discuss PHP and JavaScript redirection methods here.

We will be using Location Header function to redirect a page. This script works when we have not send any php or html command to out put any thing in the browser. Care is to be taken not to send any other thing to the browser after the header redirection using location command. Here is the code.
header ("Location:"); 
/* Redirect browser to  web site */
exit; // Closes further script execution 
You can see this code above will redirect the page to a new url.

Now we will write the code for 301 redirection (page permanently moved )
header("HTTP/1.1 301 Moved Permanently");
header ("Location:");
If we send any html tag or any other data to the browser before the redirection command, then we will get an error message like this

Warning: Cannot modify header information - 
headers already sent by (output started at L:\php_files\t\test6.php:13) in L:\php_files\t\test6.php on line 14

Checking header before redirecting

We can check weather header is sent to browser or not by using php function headers_sent(). This function will return true of false based on the status of the buffer. Read here to know more about headers_sent() and output buffers in PHP. Now here is the script to check the headers status and accordingly execute redirect code.
if (!headers_sent()) {
// No header sent , so you can use PHP to redirect //

header("HTTP/1.1 301 Moved Permanently");
header ("Location: mynewpage1.html");


// Header already sent, so use JavaScript to redirect //
print "<script>";
print " self.location='mynewpage2.html';";
print "</script>";
By using JavaScript also the redirection can be done. Here is the code printing the javascript code for the browser to redirect. But this will work if JavaScript is enabled in the browser.
print "<script>";
print " self.location='mynewpage.html';"; print "</script>";
You can read about Meta Redirect here
PHP Form Redirecting to HTTPS Conditional Redirection

Subscribe to our YouTube Channel here


* indicates required
Subscribe to plus2net

    Post your comments , suggestion , error , requirements etc here

    PHP video Tutorials
    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2024 All rights reserved worldwide Privacy Policy Disclaimer