PHP unserialize() is a builtin function in PHP7 which takes a single serialized variable and converts it back into a PHP value.
This feature seeks to provide better security when unserializing objects on untrusted data. It prevents possible code injections by enabling the developer to whitelist classes that can be unserialized.
Syntax:
1 | unserialize(string1) |
1 2 3 4 5 6 | $serialized_data = serialize(array('Math', 'Language', 'Science')); echo $serialized_data . '<br>'; // Unserialize the data $var1 = unserialize($serialized_data); // Show the unserialized data; var_dump ($var1); |
Output:
a:3:{i:0;s:4:”Math”;i:1;s:8:”Language”;i:2;s:7:”Science”;}
array(3) { [0]=> string(4) “Math” [1]=> string(8) “Language” [2]=> string(7) “Science” }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | $conn = odbc_connect("webdb", "php", "chicken"); $stmt = odbc_prepare($conn, "SELECT data FROM sessions WHERE id = ?"); $sqldata = array($_SERVER['PHP_AUTH_USER']); if (!odbc_execute($stmt, $sqldata) || !odbc_fetch_into($stmt, $tmp)) { // if the execute or fetch fails, initialize to empty array $session_data = array(); } else { // we should now have the serialized data in $tmp[0]. $session_data = unserialize($tmp[0]); if (!is_array($session_data)) { // something went wrong, initialize to empty array $session_data = array(); } } |
Here’s a simple function to get the class of a serialized string (that is, the type of object that will be returned if it’s unserialized().
1 2 3 4 5 6 | function get_serial_class($serial) { $types = array('s' => 'string', 'a' => 'array', 'b' => 'bool', 'i' => 'int', 'd' => 'float', 'N;' => 'NULL'); $parts = explode(':', $serial, 4); return isset($types[$parts[0]]) ? $types[$parts[0]] : trim($parts[2], '"'); } |
If you like FreeWebMentor and you would like to contribute, you can write an article and mail your article to [email protected] Your article will appear on the FreeWebMentor main page and help other developers.