How to detect if headers are already sent in PHP
-
I’m sure most of us have encountered the following error message while playing with the header function in PHP
“Cannot modify header information - headers already sent by …”
How can we detect whether the script has already sent out headers? PHP has a function headers_sent() which allows you to check if the headers are already sent out before you take any action. Here’s how you could use the function in your code:
if(headers_sent())
{ //if headers already sent out print some message.
echo "Please go to yahoo.com“;
}
else{
//send the user automatically to test.php
header(’Location: http://yahoo.com’);
}The code above checks to see if PHP has already sent out headers anywhere else. If so, the script will print a message on screen, else the user is automatically redirected to the yahoo.com.
Advertisement
1 Comment
Leave a Comment
























January 22nd, 2008 at 8:34 pm
better:
function safeRedirect($url) {
if(headers_sent()) {
echo “Please go to “.$url.”“;
echo “\n”;
echo “window.location.href=’”.$url.”‘;\n”;
echo “\n”;
echo “\n”;
echo “\n”;
}
else{
header(’Location: ‘.$url);
}
exit;
}
Don’t forget the closing ‘exit’, otherwise the script will continue executing.