Hire a web Developer and Designer to upgrade and boost your online presence with cutting edge Technologies

Monday, November 28, 2011

php header() function not working!

I was going nuts to find the problem why did the header() function didn’t redirect my page in some instance and did in others! Luckily I found this function ‘headers_sent()’ which will tell you if at any given point any headers were sent. If the headers were sent from some other file then this function will give you the file name and the line number from where the unexpected header was sent. Very useful and neat. See the example below, it is from php.net manual page.
Consider the following scenario,
// Sign out
signOut();
// Redirect back to the main page
header(“Location: http://toronto.eclassifieds4u.com/main“);
?>

If for some reason, the header() call to redirect is not working, there won’t be any error messages, making it difficult to debug. However, using headers_sent(), you may easily find the source of the problem.
// Sign out
signOut();
/*
* If headers were already sent for some reason,
* the upcoming call to header() will not work…
*/
if(headers_sent($file, $line)){
// … where were the mysterious headers sent from?
echo “Headers were already sent in $file on line $line…”;
}

// Redirect back to the main page
header(“Location: http://toronto.eclassifieds4u.com/main“);
?>

As the documentation states, “header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP.” In the above debugging solution, you will find out exactly where any of these problematic output or blank lines exist. You should then be able to resolve the issues with much more ease than if you hunted for the problems aimlessly.

No comments:

Post a Comment