It is interesting that it is very tricky to code in PHP sometimes. Take the openssl_pkcs7_verify function.
It has a “mixed” return type:

Returns TRUE if the signature is verified, FALSE if it is not correct (the message has been tampered with, or the signing certificate is invalid), or -1 on error.

So the first instinct is, at least for me, to test the return value of the function like this:

// success
// fail

This unfortunately does not work as expected, as -1 also evaluates to TRUE here. So the correct way to “cast” this return value to a boolean is with code like this:

$result = openssl_pkcs7_verify(...);
$bool_result = ($result == 1) ? TRUE : FALSE;

Now suppose you have this “true” boolean value, and you want to print the result. A possible approach would be like this:

$res = FALSE;
echo "Result: " . ($res) ? "VALID" : "INVALID";

This code always prints VALID, not the expected Result: INVALID, because the string concatenation is evaluated, not the variable $res itself. So no matter what the result is in $res, it always prints VALID, which can be a bit tricky if you are not paying close attention and ran out of coffee :). To fix this, you obviously need to add brackets like this:

$res = FALSE;
echo "Result: " . (($res) ? "VALID" : "INVALID");

I guess I should really program regularly to not forget all this stuff 🙂


One thought on “PHP SNAFUs

  1. First, the ternary operator is a code smell and should not be used in the first place (not only according to me, but also according to verifications tools like CheckStyle for Java… in the end I’m a Java developer).
    Secondly, isn’t there an operator which you should use for tests lik these? If I remember correctly, you should write (in case of your example, where the return value is either ‘true’ or -1):
    if(openssl_pkcs7_verify(…) === true)
    // success
    // fail

    Of course, that’s one of the major downsides of dynamic languages like PHP.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s