Mar 19

Write PHP Properly

Categories:
Tags:
Published:
3:59pm on Friday 19th March, 2010

For your reading pleasure this week, I bring you two cautionary tales on the importance of not taking shortcuts in your PHP code, or making assumptions about your (future) hosting environment.

Short tags off

For years I’ve been using PHP’s short tags to write out variables within HTML. For this habit I at least partially blame the CodeIgniter documentation, which uses short tags liberally to illustrate how to output variables set in the controller into a view file. For example:

<p>Welcome back, <?= $name ?>!</p>

Unfortunately this approach falls down when you find yourself deploying to a server that has had PHP compiled with short tag support off. The above code will not be parsed by the PHP engine… but the presence of angle-brackets will mean that you won’t see the unparsed output on the web page; so you end up with blank spaces, viz:

Welcome back, !

The ‘fix’ for this laziness is, of course, not to use short tags, even when outputting the simplest of variables:

<p>Welcome back, <?php echo $name; ?>!</p>

It is also a good practice to get into in readiness for PHP6, which will be removing the ability to use short tags altogether.

Don’t rely on truthy and falsey values

Like several other languages, PHP has a concept of truthiness and falsiness when it comes to evaluating boolean expressions. The number zero, an empty string, NULL or undefined will all evaluate to FALSE in a simple expression:

<?php
$x = 0;
$y = ’‘;
if ($x || $y || $z) {
  echo "This will not be displayed";
}
?>

(Yes, I know you can test if a variable is actually FALSE by using the triple-equals sign === in the conditional, but that’s not what this point is about.)

So we know that we can rely on PHP returning FALSE whenever we test a non-existing, empty or zero variable. Using this knowledge, we can check for the presence of incoming settings before doing things:

<?php if ($_GET[‘foo’]): ?>
  <p>You submitted the foo item.</p>
<?php endif; ?>

We can even write quite neat little loops using array indices:

<?php
while ($myarr[0])
{
  process_item(array_shift($myarr));
}
?>

So where’s the problem here? Well, all of those tests for non-existent variables or array items will throw a PHP E_NOTICE level error. Usually this isn’t a problem; most apps and PHP installations set the default error reporting value to E_ALL & ~E_NOTICE, which is to say they do not include E_NOTICE errors. No errors are shown on your web pages, and everything is fine.

That is, until you notice that the error_log on your live server has filled up with over a gigabyte of PHP errors per day. Yup, it’s another server configuration issue, this time one that writes every single notice to a text file. And if, like me, you were relying on the above behaviour then that text file gets very big, very fast.

To fix this problem just takes a little more discipline when coding. In short, always check for the presence of a variable or array key before checking its value:

<?php if (isset($_GET[‘foo’]) && $_GET[‘foo’] == ‘bar’): ?>
  <p>You submitted the foo item.</p>
<?php endif; ?>

Now the first part of the conditional—isset($_GET[‘foo’])—will fail, and the second part with the non-existent array key will never be evaluated.

I'd love to hear what you think - please use the form below to leave your comments. Some HTML is permitted: b, i, em, del, ins, strong, pre, code, blockquote, abbr. URLs or email addresses will be automatically converted into links.

Comment Form

  1. Derek Allard's Gravatar

    Derek Allard at 5:36pm on 19th March, 2010 #

    I don’t disagree with your short tags advice, however in the case of CI:

    http://codeigniter.com/user_guide/general/alternative_php.html

    CodeIgniter will optionally rewrite short tags on-the-fly, allowing you to use that syntax even if your server doesn’t support it. This feature can be enabled in your config/config.php file.
  2. JR's Gravatar

    JR at 2:36pm on 24th March, 2010 #

    Short tags are bad policy and make your code less portable for one. Zend’s coding standard at http://framework.zend.com/manual/en/coding-standard.html is a good guide for how to write/format your code.

  3. binay's Gravatar

    binay at 1:50pm on 30th March, 2010 #

    nice tips

  4. Arvind Kumar's Gravatar

    Arvind Kumar at 12:49am on 3rd April, 2010 #

    Things i always wanted my developers to follow but never tried to write them in my blog, due to my laziness! You have inspired me to write such ‘SMALL’ things and i’ll be doing it regularly now on. Thanks a lot!

  5. Antalya Travesti's Gravatar

    Antalya Travesti at 7:35am on 1st May, 2010 #

    CodeIgniter will optionally rewrite short tags on-the-fly, allowing ?