It’s very frustrating when you try to invent new code with your ability and errors just pop-up. I personally don’t like errors. But you know what is important in writing the code is? It’s a habit of keeping basic rules of writing code of any language (PHP, wordpress, drupal etc.) to say bye bye to errors.
Here I am talking about the most common error developer face:
“Warning: Cannot modify header information – Header already sent by (Output started at /controller/index.php: #) in view.php on line #”
Don’t worry about it, we got a solution for you.
Let’s see first why this error even occurs:
- When you try to output anything before header output. Yes, remember headers must be sent before any page/output. When PHP receives its output, it will flush all collected headers.
- Make sure headers will be first to send before any of your echo or print
- Extra spaces before <?php and after ?>
- While dealing with session or cookie, when session is started again or is sent after any output, it will generate an error.
- When in long block of PHP you use multiple closing and opening PHP tags.
- Modifying header information after HTML has already been displayed to client.
How to know from where error is actually generated?
As you can see the error I have specified above, you will clearly know about the line number of your code that prompts error.
Here #, suggests a line number.
For ex: “Warning: Cannot modify header information – headers already sent by (output started at /www/page.php:7) in /www/page.php on line 50”
You can see that our attempt on line 50 to modify header information is failed due to line number 7.
How to fix the error?
- First, check for extra spaces in your code as well as before and after of PHP tags – <?php and ?>. Remove them all. They may cause error.
- In case of session start session and output buffering at top:
- Remove extra closing and opening PHP tags in case of long block of code.
- Do not echo anything before header:
echo "say hello";
- If you required to redirect your page with some redirection message, then try:
echo '<h1>Wait for a while, we are securely moving you...</h1>';
Or you can use
<meta http-equiv=”Refresh” content="2; url=mypage.html”>
echo "<script> location.replace("target.html"); </script>"
Find this error in detail over here: https://stackoverflow.com/questions/8028957/how-to-fix-headers-already-sent-error-in-php
Do not forget to remove extra spaces even if you paste code from somewhere or write your own. With basic understanding of functions and their working can save you from headache of errors.
Hope this helps you. Best of luck for you code!