PHP Header Location – Page Not found Error.

Recently I faced a weird issue with the PHP header location function. I had a line of code in my file like,
Code: header(‘location:mypage.php’);
In firefox/geeko browsers it is working fine. but in IE when it tries to redirect the page it is showing a “page not found error”. I am pretty sure that the page is exist in my server and I checked the spelling and case also. everything is fine. following is the header call i am using. I searched in google and asked few of my friends. Also I
found lots of post related to this in forums and all. But didn’t see a good solution anywhere. Finally, from the Php header manual page itself, I got the solution.
The reason behind this mysterious behaviour is, HTTP/1.1 requires an absolute URI as argument to Location: including the scheme, hostname and absolute path, but some clients accept relative URIs. You can usually use $_SERVER['HTTP_HOST'], $_SERVER['PHP_SELF'] and dirname() to make an absolute URI from a relative one yourself:
<?php
$host = $_SERVER['HTTP_HOST'];
$uri = rtrim(dirname($_SERVER['PHP_SELF']), ‘/\\’);
$extra = ‘mypage.php’;
header(“Location: http://$host$uri/$extra”);
exit;
?>
Also, It would be good if you use a capital L and put a space before the url like
header(“Location: http://$host$uri/$extra”);
This solves my issue. I never used absolute path with header location in any of my projects. This is the first time I am getting this error. But, going forward, i am thinking that it would be good if i use absolute paths in my location urls. I don’t know any other impact for this or not.
Filed under: PHP
