Tuesday, February 14, 2012

Handling PHP Warning: Cannot modify header information - headers already sent

This can be a nightmare for a developer if they want things done quick. It is caused when a page/file which has already been requested get requested (require_once, require, include) again in the same script.
At times a developer need to get the thing to work at all costs and the only way to achieve is code hack. Simply tell PHP to keep its warning off just before the include or require statement and its warning on after it.
For instance I am requiring a file named cannotmodiy.php and the error occurs. The solution is
<?php

error_reporting(0);
require_once 'cannotmodify.php';
error_reporting(E_ALL & ~E_NOTICE & ~E_WARNING);
// other codes continue

?>
So you tell php, hey! I know what I am doing. Keep your mouth shut. Then after that you tell php to speak of any errors it sees. As simple as that.