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.
This will output:
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:
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:
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.
0 comments:
Post a Comment