PHP 301 Redirect Function with Headers Check and Javascript Fallback
May 22nd, 2008Read More php, search engine optimisation
If you are changing your URL structure, for example when moving to a search engine friendly URLs system, you need to be able to let Google and all the other search engines that the page has moved to the new URL. You really don't want to display the same content on two URLs
So to achieve this we can do what is called a 301 redirect. This is a special redirect message which basically says "has permanently moved to". By doing this, all of the search engine power, rank or whatever you want to call it will be directly transferred to the new URL.
However
Sometimes your script might spit out the headers earlier than you expect. If this happens then your site will fail completely to load with a fatal error along the lines of
warning: Cannot modify header information - headers already sent by (output started at ....
We really don't want this to happen, so what we can do is wrap the redirection in a headers_sent check and then fall back to a javascript redirect if headers have been sent for some reason. This is belt and braces logic.
Note script tags need spaces removing
-
function requrl_check($correct_url, $delay=3){
-
$request_url = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
-
if($request_url != $correct_url){
-
}else{
-
echo "<h3>The Page $request_url has Moved</h3>
-
<a href=$correct_url>$correct_url</a>";
-
echo '<h3>Now Refreshing in ' . $delay . ' Seconds</h3>Refreshing to:<br>' . $correct_url . '<s c r i p t type="text/JavaScript"><!--
-
setTimeout("location.href = \'' . $correct_url . '\';",' . ($delay * 1000) . ');
-
--> </s c r i p t>';
-
}
-
}
-
}
tidy
Further Reading:
www.stuntdubl.com
www.intertwingly.ne
webgasm.actiononline.biz
www.techcounter.com
www.chiropractichomepage.com
123howtoguide.com
searchblog.tamar.com
