Home >Backend Development >PHP Tutorial >How Can I Deserialize a Serialized String in PHP?

How Can I Deserialize a Serialized String in PHP?

Barbara Streisand
Barbara StreisandOriginal
2024-12-02 20:41:12791browse

How Can I Deserialize a Serialized String in PHP?

Understanding Serialization and Unserialization

You've encountered a serialized string, which is represented as follows:

a:2:{i:0;s:7:"Abogado";i:1;s:7:"Notario";}

To retrieve the array stored within this string, you must perform deserialization using the unserialize() function:

$str = 'a:2:{i:0;s:7:"Abogado";i:1;s:7:"Notario";}';
print_r(unserialize($str));

This operation will produce the following output:

Array ( [0] => Abogado [1] => Notario )

Manual Notes:

  • Be cautious as unserialize() returns FALSE for both errors and deserialization of FALSE value. To handle this, compare str with serialize(false) or catch the issued E_NOTICE.
  • Exercise vigilance when passing user-provided input to unserialize(). This can potentially execute malicious code. Consider employing a secure data exchange format like JSON (json_decode() and json_encode()).

The above is the detailed content of How Can I Deserialize a Serialized String in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn