[thelist] Tip: whitespace in included PHP causes header() calls tofail

Burhan Khalid thelist at meidomus.com
Sat Aug 20 02:56:17 CDT 2005

Paul Bennett wrote:
> <tip type="php development">
> Error Reporting is your friend.
> Turning error reporting right up on test servers or during development will literally save you hours of time. Lower levels of error reporting won't report undeclared variables, call's to Header() when there's white space already outputted to the browser and a hundred other errors which can stop things working properly. 
> If you don't have access to php.ini (i.e.: on a shared server) you can turn error reporting up at runtime via:
> ini_set('error_reporting', E_ALL); 
> </tip>

Also remember to turn on 'display_errors' otherwise nothing will be 

In addition, if you have this on top of a script that has a header() 
call, any type of error (for example, a notice) will cause the header() 
call to fail because the output from the error will be sent to the browser.



   error_reporting(E_ALL); //similar to above

   if ($_GET['code'] == '123')
     echo 'Correct code';
   } else {
     header('Location: http://www.google.com/');

When you request this page directly, you will get a notice similar to 
'Undefined key 'code' in array $_GET on Line ...' which will be output 
to the browser, causing the the header() call to fail with the a notice 
similar to 'Cannot send headers. Output already started at line...'

Need to watch out for things like the above, which can cause some great 
head scratching for beginners.

There are a number of ways to avoid simple notices such as 'undefined 
key' notices.  I'll list the most common that I have seen:

1. Turn up your error reporting level to only report fatal errors, or to 
filter out notices.

2. Use the @ operator (error suppression operator). if (@$_GET['code'] 
== '123')

3. Use a function such as array_key_exists or isset:
    if (array_key_exists('code',$_GET) && $_GET['code'] == '123')
    (this is my favorite method, and the one I tend to recommend)

Hopefully this helps,

More information about the thelist mailing list