Monthly Archives: August 2010

Valid Syntax errors: Part 1

It took me about an hour to spot a strange behaviour in my PHP skript:

Have a look at this code:

$foo = array ( 'a', 'b', 'c' );
foreach ( $foo as $bar );
    echo $bar . "\n";
// Expected Output:
// a
// b
// c
// Actual Output: 
// c

What happened?

Would I have used phpcs it would have been obvious. I used a semicolon instead of a bracket after the foreach statement.

So instead of calling the echo command with each iteration the foreach silently iterated through $foo and assigned $bar on each iteration. That left $bar with the last value of the array that gave the strange output.

I can not actually remember whether there had been closing brackets but I did not get an Error regarding that.

phpcs would have detected the missing brackets — if that would be observed by the used sniff.

More on phpcs later.

unserialize values

Last week I had the problem, that – due to a wrong database-entry – a serialized value got scrambled. And due to that (and some missconfiguration of the server) the application broke. Instead of a search result the user simply got an error message about not being able to unserialize the value due to an offset-error.

So how could I avoid the error (which actually is a notice) being thrown and besides that get to know whether unserializing worked or not?

The hack I finaly came up with is as follows:

  • suppress the notice in any way
  • check whether the returned value is a boolean false and the given string is ‘b:0;’ (which represents a boolean false in a serialized string).
  • If so, the unserialize() failed, so lets throw an InvalidArgumentException

And here it is:

public function my_unserialize ( $value )
    $unserialized = @unserialize ( $value );
    if ( false === $unserialized && 'b:0;' !== $value ) {
        $le = error_get_last ();
        throw new InvalidArgumentException ( $le['message'] );
    return $unserialized;