PHP Redirect

This article will show you how you can redirect users to a new webpage instead of the original one using PHP. This technique is especially useful when you are website is down or you have moved your content to a new location and you want to redirect your users accordingly.

To redirect with PHP check out the code given below. Place this code on the webpage on which you want to perform redirection.

<?php

header( 'Location: http://www.yourdomain.com/new-page.php' ) ;

?>

Replace http://www.yourdomain.com/new-page.php with your own URL. One very important thing to keep in mind is that there should be no html tags or php echo/print commands present before this header() function else your code (redirection) wont execute and it will report a warning like this - Warning: Cannot modify header information - headers already sent by . . . For instance this code won't work - 

 

<?php

echo "Testing";

header( 'Location: http://www.yourdomain.com/new-page.php' ) ;

?>

And there will be no redirection performed.

You can also perform a 301 (permanent) PHP Redirect if you have moved your content to a new webpage permanently. To do so use the following code - 

<?php

header( "HTTP/1.1 301 Moved Permanently" );

header( 'Location: http://www.yourdomain.com/new-page.php' ) ;

?>

Similarly you can perform a 302 (temporary) PHP Redirect as shown below - 

 

<?php

header( "HTTP/1.1 302 Moved Temporarily" );

header( 'Location: http://www.yourdomain.com/new-page.php' ) ;

?>

To use PHP to handle requests for missing files (using the ErrorDocument directive) a header can be sent like this - 

 

<?php

header("HTTP/1.0 404 Not Found");

?>

 

Tags: