How to fix Headers already sent error in PHP
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
The "Headers already sent" error in PHP is a common issue that typically occurs when your script tries to send an HTTP header after its data has already been sent to the output. Understanding and fixing this problem involves a good grasp of how PHP handles output and headers.
Understanding the Error
HTTP headers must be sent before any output is generated. This includes not just HTML or text, but even invisible characters like whitespaces or line breaks. The "Headers already sent" error usually appears because there's some output sent to the browser before the PHP code attempts to modify the headers.
Typical error messages look like:
This message indicates that output originating from file.php on the specified line prevents additional headers from being sent.
Common Causes
- Whitespace Before Opening PHP Tags: Leading whitespaces or lines before
<?phpin your PHP files. - Echo Statements: Using
echoorprintbefore setting headers. - BOM Character: Byte Order Mark character at the start of the file in UTF-8 files.
- Closing PHP Tags:
?>at the end of files, which can inadvertently lead to appending trailing white spaces.
Solutions
Whitespace Before Opening PHP Tags
Ensure no whitespaces, new lines, or characters exist before the opening <?php tag in your file. This is a habitual error, especially in scripts with multiple includes or requires.
Premature Output
Avoid using any PHP commands that produce output (like echo, print, var_dump, etc.) before header functions (header(), session_start(), setcookie(), etc.).
File Encoding
Save your PHP files without a Byte Order Mark (BOM). Most modern text editors (like VSCode, Sublime Text) and IDEs provide an option to save files using "UTF-8 without BOM" encoding.
Closing PHP Tags
You can optionally omit the closing ?> tag in a pure PHP file to avoid accidental whitespace or new lines after it.
Debugging the Error
If you aren't sure where the output started, follow these steps:
- Check the Error Message: It tells you the exact file and line number where output started.
- Backtrack from There: Look at that line and anything before it for output.
- Buffered Output: Utilize output buffering functions like
ob_start()at the beginning of your script which can give you more control.
Using Output Buffering
Output buffering collects all the output data but doesn't send it to the client until you flush the buffer. This gives you time to send all needed headers before any actual output. You start output buffering by calling ob_start() and end it with ob_end_flush().
Table of Common Solutions
| Issue | Solution |
White space before <?php | Remove any spaces, new lines, or characters before <?php. |
Using echo/print before headers | Move all echo/print statements after header modifications. |
| BOM in UTF-8 file | Save the file as "UTF-8 without BOM". |
Trailing white space after ?> | Remove closing ?> in pure PHP files, or ensure no trailing spaces. |
Additional Tips
- Error Logging: Instead of relying on front-end displayed errors, log errors to a file for review.
- Consistent Practices: Establish coding standards concerning header management and file encoding in your development team.
By understanding how and why the "Headers already sent" error occurs and addressing it with appropriate practices, you can manage headers effectively in your PHP applications.
Related reading
- How to fix Helm installation failed complaning about a nil pointer evaluating interface on fullnameOverride
- How to fix Incorrect string value errors?
- How to fix ipykernel_launcher.py error unrecognized arguments in jupyter?
- How to fix issue of 'Unable to connect to the server EOF' Kubernetes - Kubectl
- HOW TO FIX IT? AttributeError module 'keras.preprocessing.image' has no attribute 'load_img
- How to fix java.io.NotSerializableException org.apache.kafka.clients.consumer.ConsumerRecord in Spark Streaming Kafka Consumer?
- How to fix java.lang.OutOfMemoryError Direct buffer memory in flink kafka consumer
- How to fix java.net.SocketException Broken pipe?
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.