Skip to content
Udecode Udecode
Developer Guides

PHP Serialize and Unserialize Explained Safely

Understand PHP serialization, when serialized data is useful, and why untrusted serialized input requires special care.

By Udecode AdministratorSeptember 8, 20262 min read

Serialization converts an in-memory value into a representation that can be stored or transported. PHP has built-in serialization functions, which can be useful for controlled application data. Unserialization deserves extra care because serialized PHP data can represent more than simple scalar values.

What is serialization?

Serialization turns a value such as an array into a string representation. The result can be stored in a database or file and later reconstructed. The exact format is PHP-specific and should not be treated as a universal data interchange format.

When PHP serialization makes sense

It can be useful for internal caches, legacy application formats, and tightly controlled data where PHP is both the producer and consumer. For public APIs, JSON is usually a better interoperability choice.

Why unserializing untrusted data is risky

PHP object serialization has historically been associated with gadget-chain risks when applications unserialize attacker-controlled values and have dangerous magic methods or classes available. Modern applications should avoid unserializing untrusted input and use safer data formats where possible.

Safer design

  • Do not accept arbitrary serialized PHP values from untrusted users.
  • Prefer JSON for cross-system data exchange.
  • When legacy serialized data must be read, disable class instantiation where supported.
  • Validate the resulting data before using it in application logic.

Serialization versus JSON

JSON is language-independent and widely supported. PHP serialization preserves PHP-specific structures and therefore has a narrower use case. Choose the format based on interoperability, security, and lifecycle requirements rather than convenience alone.

Frequently asked questions

Is PHP serialization the same as JSON?

No. PHP serialization is a PHP-specific representation, while JSON is a broadly interoperable text format.

Can I unserialize user input?

Avoid unserializing untrusted input. Prefer JSON or another safe format designed for the boundary between users and your application.

Why is unserialize useful at all?

It remains useful for controlled legacy or internal PHP data where its format and trust boundaries are well understood.

Related articles