Headers already sent by PHP
While working in PHP, you might come to this weird situation where you want to redirect to a page or send header information and you get this warning 'Headers already sent'. In this post, I am trying to help you get this issue solved.
The first thing you can do is check if headers have already been sent or not. To check this the function you need to use is headers_sent(). For example:
if(!headers_sent()){This is just a simple method to test if headers were sent or not. Now what we wanted to do here is to send headers even if the headers went sent. To do this, there are a few steps. First thing to do is start output buffering on top of the page. This can be done by the PHP function ob_start();. So output buffering has been enabled. Now we want to check if headers were sent if they were sent then we need to clear them. TO do this we check for the status, and if its not clear then we do clear as follows:
//headers not sent you can send header
}else{
//headers already sent
}
while (ob_get_status()){To sum up, if you are getting headers already sent then you need to have your PHP file as follows:
ob_end_clean();
}
//now you can send header again.
<?phpThis should solve the issue.
ob_start();
//all your code goes here
while(ob_get_status()){
ob_end_clean();
}
header('location:http://example.com') //to send headers
//your codes go here to
?>
Comments
Post a Comment