Solve "Cannot modify header information - headers already sent by *.php"
Warning: Cannot modify header information - headers already sent by somefile.php (output started at somefile.php:###) in somefile.php on line ###This Warning is shown by PHP when you use the header function to output headers or use the setcookie function to set cookies after any echo or content which is not inside PHP tag.
<?php echo "Hello World"; header("Location: /redirect.php"); ?>
Hello World !!! <?php header("Location: /redirect.php");?>Both should throw this warning. You can disable this warning by turning the error_reporting to OFF using
error_reporting(0);, which is pretty much the not way of doing things. In HTTP Headers are sent before the actual content so if you are going to use header function after outputting the contents, it is likely to not work.
How do I solve this Warning Cannot Modify Header Information ?In order to solve this issue you have to make sure you dont echo or print any output before using header or setcookie function. Make sure the control passes through these functions and then to the output part.
I am sure I dont output anything before calling header or setcookieJust see all your files for white spaces or empty new lines. For example if you include a file before using the header or setcookie functions, make sure the file does not have a closing php tag (?>) at the end of the file. This is recommended by PHP so that stray white space or new line characters at the end of this included file gets outputted.
//<-- A new line on top ! Oops. <?php header("Location: /redirect.php");?> // <-- A blank line at the end?
I still want to output first and then use header functionIn that case you can use output buffering functions to buffer your output automatically before senting any output and the output is sent as a chunk at the end. The following code snippet shows this :
<?php ob_start(); ?> Hello World !!! <?php setcookie("name","value",100); ?> Again !!! <?php ob_end_flush(); ?>
But my code is already done and I dont want to add ob_* functions to it !You can turn on buffering in PHP on by default using php.ini. Look for output_buffering , The following shows the mentioned part of the php.ini file. Set the value as On and restart Apache server.
; Output buffering allows you to send header lines (including cookies) even ; after you send body content, at the price of slowing PHP's output layer a ; bit. You can enable output buffering during runtime by calling the output ; buffering functions. You can also enable output buffering for all files by ; setting this directive to On. If you wish to limit the size of the buffer ; to a certain size - you can use a maximum number of bytes instead of 'On', as ; a value for this directive (e.g., output_buffering=4096). output_buffering = On
Video to fix your warning cannot modify header information
Warning Cannot Modify Header Information :) 17 Mar, 2010