Home / PHP’s unserialize function and E_NOTICE

PHP’s unserialize function and E_NOTICE

PHP has the serialize and unserialize functions for converting data into a storable value (for example being able to store an array in a database field). An issue with the unserialize function is that it will issue an E_NOTICE error if the data is not unserializeable. This post looks at how to prevent the notices from being displayed if you have error reporting at a level that will show notices.

The problem

The following code snippet sets error reporting to a level that will show notices, and then attempts to unserialize a string which is not serialized.

error_reporting(E_ALL);
$y = unserialize('asdf');
if($y) {
    // do something
}
else {
    // do something else
}

This will output:

Notice: unserialize(): Error at offset 0 of 4 bytes in /path/to/file.php on line 9

The solution

The unserialize manual page states that "It is possible to catch this special case by comparing str with serialize(false) or by catching the issued E_NOTICE." However you cannot catch E_NOTICES with try…catch syntax.

If your data had been serialized and you are now unserializing it, you shouldn’t normally have any issues but it is possible that they can happen, and if they do then it’s probably better to suppress the E_NOTICE information.

The easiest way to do this is with the @ operator:

$y = @unserialize('asdf');

The notice will no longer be displayed, and testing if $y is false will let you know if the value was successfully unserialized.

Another solution

I prefer the simplicity of the @ error-suppression operator, but another approach is like this:

$error_reporting = error_reporting(error_reporting() ^ E_NOTICE);

$y = unserialize('asdf');
if($y) {
    // do something
}
else {
    // do something else
}

error_reporting($error_reporting);

This approach stores the current error reporting level in a variable; changes the reporting level to not include E_NOTICE and then restores the error reporting level afterwards.