unserialize()

unserialize() — Creates a PHP value from a stored representation.

Built-in function of PHP 8.5. The manual lists it as available in PHP 4, PHP 5, PHP 7, PHP 8. This page is the reference card: signature, parameters and return value, plus the changelog and the example the manual provides.

What it does

Do not pass untrusted user input to unserialize() regardless of the options value of allowed_classes. Unserialization can result in code being loaded and executed due to object instantiation and autoloading, and a malicious user may be able to exploit this. Use a safe, standard data interchange format such as JSON (via json_decode() and json_encode()) if you need to pass serialized data to the user.

Signature

unserialize(string $data, array $options = []): mixed

Parameters

ParameterTypeWhat it takes
$datastringThe serialized string.
$optionsarrayAny options to be provided to unserialize(), as an associative array.

Return value

The converted value is returned, and can be a bool, int, float, string, array or object. In case the passed string is not unserializeable, false is returned and E_WARNING is issued.

Example

A runnable snippet:

// Here, we use unserialize() to load session data to the // $session_data array from the string selected from a database. // This example complements the one described with serialize(). $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(); } }

Changelog

VersionChange
8.4.0Now throws TypeError and ValueError if the allowed_classes element of options is neither an array of class names nor a bool.
8.4.0Unserializing strings using the uppercase "S" tag is now deprecated; use the lowercase "s" tag instead.
8.3.0Now emits E_WARNING when the input string has unconsumed data.
8.3.0Now emits E_WARNING when the passed string is not unserializeable; previously E_NOTICE was emitted.
7.4.0Added the max_depth element of options to set the maximum depth of structures permitted during unserialization.
7.1.0The allowed_classes element of options is now strictly typed, i.e. if anything other than an array or a bool is given, unserialize() returns false and issues an E_WARNING.

See also

json_encode(), json_decode(), hash_hmac(), serialize()

All PHP 8.5 built-in functions

Reference card built from the PHP manual page unserialize() (PHP documentation, CC BY 3.0). The page is generated from the manual, so the wording of the parameter and return value text follows php.net.