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

Burhan Khalid thelist at meidomus.com
Sat Aug 20 02:33:18 CDT 2005


Matt Warden wrote:
> -----BEGIN PGP SIGNED MESSAGE-----
> Hash: SHA1
> 
> Ian Anderson wrote:
> 
>>In PHP, calls to header( "Location: whatever.php" ) were failing
>>silently whenever an include file was used to validate the user's
>>session data.
>>
>>I thought it was something I was doing with cookies or session_start()
>>in my included file, but no...
>>
>>Turned out there was a space *after* the closing "?> " in the included
>>file, which was getting written to the browser as unintentional output
>>at the start of the HTML. Of course, calls affecting HTTP header will
>>not work if output has already been written to the browser.
> 
> 
> This is why you should never use the closing ?> in include files (it's
> optional).

This is bad practice to omit the closing ?> just like its bad practice 
to use <?=

What instead you should do is, ensure that you have no leading or 
trailing whitespaces (any decent editor has an option to show whitespace).

In addition, always give the full URI to a Location: header. Location: 
foo.php (although works) is not the recommended way:

"Note:  HTTP/1.1 requires an absolute URI as argument to Location: 
including the scheme, hostname and absolute path, but some clients 
accept relative URIs. You can usually use $_SERVER['HTTP_HOST'], 
$_SERVER['PHP_SELF']  and dirname() to make an absolute URI from a 
relative one yourself"

Other functions to help debugging header related issues are 
headers_sent() and headers_list().  You can also use output buffering to 
avoid the headers already sent "error".

Regards,
Burhan


More information about the thelist mailing list