1. ‘Cannot modify header information’
I come across this one every so often – you create a quick php file to redirect the user somewhere at some juncture, you might get this message, and it’s a little confusing.
It essentially means that the php script is trying to write header information to redirect the user, but the header information has already been sent to the browser when you requested the page!
Check the <?php tag at the start of your php file has no spaces preceding it!
PHP doesn’t really have a debugger, so var_dump is your friend. I use this so often I have it mapped to a macro in netbeans. Put
and it’ll output the variable in detail.
You can use this in conjunction with $_GET, $_POST and $_SESSION to get all sorts of debug information! I find PHP tutorials don’t mention this enough, so there you go.
Chuck an ‘exit;’ after var_dump (e.g.
in your code, and it’ll quit at the point that this is called, making things hopefully a little clearer as to where your code’s going wrong.
3. Output buffering
Sometimes you may need to call functions that automatically output data to the screen. You can use an output buffer to put this in a buffer that you can later echo.
To start the buffer:
To end the buffer and put it in a ‘$output’ variable (which you can then echo out if you wish):
$output = ob_get_clean();
Read more here: http://php.net/manual/en/function.ob-start.php
4. DEBUG setting
If you ever find yourself with a white screen when you expected something to happen, and you’re running apache, make a .htaccess file (http://en.wikipedia.org/wiki/Htaccess) and put the following lines into it:
php_flag display_startup_errors on php_flag display_errors on php_flag html_errors on php_flag log_errors on
This will give you an error message for something that the PHP error handler perhaps didn’t catch, like a memory exception for example. You can put this htaccess in the folder your buggy code is in, so it doesn’t affect the rest of the site. Be careful – don’t do this with live sites or you might output some information to the user that you don’t want them to see and create a security issue!
Alright, someone must have told you about this one before, but it’s definitely worth a mention. Put
into a php script and it will echo out a load of helpful info about the php version and the software it’s running on.