Whitespace Matters!

You must keep track of your whitespace in PHP scripts. Why? HTTP headers cannot be set if you have already "printed" any characters. Stray spaces before and after segments will, among other things, prevent you from setting HTTP headers (e.g. session cookies, redirects, and so on).

This is something I run into over and over and over and over in modifying carelessly written code. Sometimes this is the work of a well intentioned developer trying to make code "more readable". Worse, this is a problem you won't catch until its too late. You can code for months or years on a project and never notice any problems. Until one day everything explodes for no obvious reason. There are huge, massive projects out there that still haven't completely learned this lesson.

Opening Demarcation

If your script contains only PHP code then it must begin with <?php at the very beginning of the file. No spaces. No new lines. <?php should be the very first characters in your new file. Don't use asptags <%, don't use shorttags <? or any other cutesy business.

Closing Demarcation

If your script contains only code and no embedded HTML markup then it must never include a ?> closing tag. Never. Ever. Yes, of course it'll work. Don't do it. Omitting the closing ?> ensures that all trailing whitespace will be in a code segment and not your output buffer.

Good Example

<?php
function helloWorld(){
    return 'Hello World!';
}
 
 
echo helloWorld();
 
 

Bad Example

 
 
<?php
function helloWorld(){
    return 'Hello World!';
}
 
echo helloWorld();
 
 
?>
 
 
 
 

Whitespace In Code

A less common problem one might encounter are simple mistakes and typos.  For example, if you copy and paste code from one editor to another you may introduce characters you can't see or fail to notice.  Always be on the lookout for things like that especially if you are copying code from another source.  I strongly urge you to configure your code editors to always display invisible characters.  For example, most code editors can display an interpunct symbol (middot) for spaces and paragraph symbols for new lines.  Also, always configure your editor to insert 4 spaces in place of the tab character to ensure code segments line up the same in all editors.

<?php
$a = 5.5; // float with value 5.5
$b = 5 . 5 // string of "55" or int of 55
 
function  myFoo(){ // non-breaking space at beginning of function name
    print "equals bar";
 
}
 
myFoo(); // fatal error: call to undefined function  myFoo()
 
---