The header already sent error in PHP is a very common error. The main reason behind header already sent is, before the redirect code starts you already have some output.
What is header, as per php.net
header() is used to send a raw HTTP header. See the » HTTP/1.1 specification for more information on HTTPheaders.
In simple terms, header is a function where you can pass some methods for the action you need done.Defining a page 404 in PHP using header for
Making status code 404 in PHP using Header
1 2 3 | <?php header("HTTP/1.0 404 Not Found"); ?> |
or redirect using header in PHP
1 2 3 4 | <?php header('Location: http://paperpencilwriteup.com/'); exit; ?> |
Here is a solution on how you can prevent header already sent error in PHP
- Make sure no output is sent (print) before the PHP redirect using the header function, be it HTML code or white space or just a new line.
- If you aren’t sure of output then do the following, right click -> click the view source. If there is any output then you will be able to recognize it.
- Use below method to redirect, which checks if header is already sent, if yes then use alternate methods to redirect12345678910if (!headers_sent())header('Location: http://paperpencilwriteup.com/');else {echo '<script type="text/javascript">';echo 'window.location.href="http://paperpencilwriteup.com/";';echo '</script>';echo '<noscript>';echo '<meta http-equiv="refresh" content="0;url=http://paperpenci writeup.com/" />';echo '</noscript>';}
If you have any issue regards header error in PHP then don’t hesitate to comment, I will help you out.
Please take a moment and contribute to the web community by sharing this article.