PHP Redirect – flexible and even scripted redirection
Aug, 30, 2008
Posted byGenerally speaking I prefer 301/302 redirects in .htaccess because I find on a domain-wide basis they are easier to manage since all redirects are in one handy file. Sometimes, though, redirection with PHP is a better fit, and since I’ve not remembered to add this little bit to my Dreamweaver Snippets, I thought maybe someone else would bee looking for the same info.
Here’s the code, and it must be placed before any HTML header information is passed:
<?php
header( ‘Location: http://www.newplacetogo.com/’ ) ;
?>
Note that according to PHP.net this will also “[return] a REDIRECT (302) status code to the browser unless some 3xx status code has already been set.” So how DO you set the status code to 301 if you don’t want the default 302?
<?php
header(“HTTP/1.1 301 Moved Permanently”);
header( ‘Location: http://www.newplacetogo.com/’ ) ;
exit;
?>
Here’s a little more complex example:
<?php
if ($myVAR == “A”)
{
header( ‘Location: http://www.newplacetogo.com/pageA.php’ ) ;
exit;
}
elseif ($myVAR == “B”)
{
header( ‘Location: http://www.newplacetogo.com/pageB.php’ ) ;
exit;
}
?>
The easiest way to make sure no HTML headers are passed before a PHP Redirect is to place it at the very top of the PHP file. If you can’t do that for some reason you may have some interesting scripting ahead.More Info on PHP.net’s PHP header manual page.
Maybe you wanted to set up a custom 404 page using .htaccess? Then read my post about using .htaccess to set a custom 404 page.
RELATED POSTS
- » Using .htaccess to set a custom 404 page
- » CSS: Use ID Selector or Classes?
- » Dreamweaver 8 'Bug': This search result cannot be displayed because
- » Expanding Dreamweaver usability with Windows/Mac OS/Linux
- » Site Design Basics - Navigation and Links
Posted in Web Design by |