We use cookies to make your experience better. To comply with the new e-Privacy directive, we need to ask for your consent to set the cookies. Learn more.
Storing Serialized Objects in PHP: Best Practices and Pitfalls
In PHP development, it's common to persist data across requests or share it between systems. One quick way to achieve this is by serializing objects and storing them—often in databases, cache systems, or session stores. While simple, this approach has pros and cons developers should be aware of.
Let’s explore what it means to store serialized objects in PHP, when it’s useful, and what you should watch out for.
What Is Object Serialization?
Serialization in PHP is the process of turning an object into a storable string format, typically using:
$serialized = serialize($myObject);
This string can be stored in a database, file, or memory store (like Redis), and later restored using:
$restored = unserialize($serialized);
The restored object maintains its structure, property values, and class name (assuming the class still exists).
When Should You Store Serialized Objects?
Sessions
PHP’s session handler uses serialized data to store objects between page loads.
Caching
Serialized objects can be cached to avoid recomputing them every time.
Temporary Persistence
For job queues or retry logic, storing the entire object state (e.g., in a DB) can be useful.
Pitfalls to Watch Out For
- Database Inflexibility
If you store serialized data in a database (e.g., MySQL), you lose the ability to query or index any of that data. inefficient and unreliable. - Class Dependency
If the class structure changes (e.g., renamed properties or class moved), unserialize() can break or behave unexpectedly
Or worse—silent failure with subtle bugs.__PHP_Incomplete_Class_Name - Security Risks
unserialize() is dangerous with untrusted input. It can be exploited to execute arbitrary code, especially if your application autoloads classes or uses magic methods like __wakeup() or __destruct().
Never unserialize data you didn’t generate yourself.
Safer Alternatives
json_encode() / json_decode()
For many use cases, especially with plain data (arrays, stdClass), JSON is a better choice:
- More portable
- Readable and debuggable
- Safer (no class dependency or execution risk)
Best Practices
- Only serialize objects you control.
- Use class_alias() to help maintain backward compatibility.
- Prefer JSON for cross-platform storage or simple data.
- Use custom serialization via Serializable interface or __sleep() / __wakeup() when needed.
- Avoid storing serialized objects in relational DBs for persistent long-term storage.
Final Thoughts
Storing serialized PHP objects is a quick and powerful technique—but one that comes with serious caveats if misused. For short-lived persistence (caching, sessions, queue payloads), it’s often fine. But for long-term, queryable, or secure storage, JSON or structured schema is usually the better path.
Stay safe, and serialize responsibly.