Wednesday, November 4, 2009

Top 5 most common PHP blunders

PHP is a very flexible language. Flexible enough that someone with no programming experience at all can create useful programs, meanwhile appeasing the needs of the formally trained OOP programmers.

Coders from either of these two groups have certainly written code that generated an error. Sometimes I just wish that either the errors were more helpful, or simply spat out a number, so you could look it up in the "this number means this error" table.

I can see it now.. "Parse error #63" and of course referencing my list of error codes that doubles as a black light poster I see error #63 reads "you left the stupid semi-colon off the end of the line again !" Some things just never change.

Anyway, here are in my opinion the most common errors PHP coders encounter, and hopefully some hints on what might be the cause.

  • #5

    Warning: Cannot modify header information - headers already sent by (output started at ...

    If you have a PHP script that tries to use the header function, or set cookies, you might have encountered this error. It's one of the few where the error message is actually helpful. The most common cause is an extra space or line either at the top or bottom of the PHP script, outside the <?php & ?> tags. Reading the error, it actually tells what file, and where the problem was caused.



  • #4

    Parse error: syntax error, unexpected T_STRING in ...

    Probably one of the most common errors, and also the least helpful. The most likely cause is the line above the one indicated in the error message is missing the semi-colon at the end.




  • #3

    Parse error: syntax error, unexpected $end in ...

    This error can be a nightmare to correct and almost always has to do with a missing closing curly bracket } You can avoid these types of problems by formatting your code as you go, lining up the opening and closing curly brackets like this...

    if ($loggedin == 1) {
    echo 'Hello '. $username;
    } 
    else 
    {
    echo 'Hello guest';
    }
    

    You will ALWAYS have the same number of opening and closing curly brackets. Another possible cause is mismatched double and single quotes in an echo or print statment, eg; echo "Oh no another error!';




  • #2

    Parse error: syntax error, unexpected 'X', expecting ',' or ';'

    Another not entirely helpful error, but usually easily fixed. Check for attempts to print/echo strings that are not surrounded by single or double quotes, like ...
    echo Oh no another error!; This error might also be the result of a missing semi-colon at the end of the preceding line.




  • #1

    Invalid argument supplied for XYZ ....

    Certainly a candidate for least helpful, this error arises when your try to do something to an array or object that doesn't exist. The actual cause can vary from simple typoes to a failure to create and populate the array/object.