Sunday, March 19, 2006

Very Useful PHP function - find out where output started!!

I have been programming with PHP for nearly three years and still I am discovering incredibly useful functions. One such that I found today was the headers_sent() function. This functoin returns a boolean value, indicating whether or not the HTTP headers have been sent and more importnatly whether output for the body of the request has started.

It is useful to know this in web programming becuase once the HTTP headers have been sent to the user and the body of the reuqest is being sent, no additional headrs can be sent and attempting to do so will fail.

But, this function does more than tell you whether the headers have been sent, it tells you when and where they have been sent. By passing two arguments to the function it will also tell use the file and line number where they were sent and the main body of the request is output.

While debugging big applications which include code from several files, I often find myself hunting for a rogue ehco or print_r statement that I was using to check data and program flow. With the headers_sent function, the offending statement can be found in seconds.

This is what I did. I edited my php.ini file to add a file to the end of all scripts using the auto_append_file directive. In this file I put three lines of code:

    
if (headers_sent($file, $line)) {
echo("<p><b>Output started by {$file} on line {$line}</b></p>");
}


Simple, elegant and extremely useful.

No comments: