serialize() / unserialize()
Also Known As
serialize()
unserialize()
PHP object serialization
TL;DR
PHP's native serialisation functions can trigger arbitrary code execution via magic methods when deserialising untrusted data.
Explanation
unserialize() reconstructs PHP objects from a string, invoking magic methods like __wakeup() and __destruct() in the process. If the serialised payload is attacker-controlled, they can craft a Property Oriented Programming (POP) chain using classes already loaded in the application to achieve arbitrary code execution — a PHP Object Injection attack. Never call unserialize() on user-supplied input. Use JSON (json_encode/json_decode) for data exchange; if serialisation is required, use authenticated, signed payloads or a safe serialisation library.
Common Misconception
✗ serialize() is safe to use for caching any PHP object. serialize()/unserialize() on untrusted data triggers PHP object injection. For caching, use json_encode() for data structures or explicitly allowlist trusted classes via unserialize($data, ['allowed_classes' => [SpecificClass::class]]).
Why It Matters
serialize() converts PHP values to a storable string representation — passing serialized user input back to unserialize() is one of PHP's most dangerous patterns, enabling object injection attacks.
Common Mistakes
- Unserializing any user-controlled data — cookies, URL parameters, database values from untrusted sources.
- Using serialize() for data exchange between systems — use JSON instead; it cannot trigger PHP object instantiation.
- Not using allowed_classes option in unserialize() to restrict which classes can be instantiated.
- Storing serialized data in cookies — the cookie is user-controlled and can be replaced with a crafted payload.
Code Examples
✗ Vulnerable
$obj = unserialize($_COOKIE['data']); // attacker-controlled
✓ Fixed
$data = json_decode(base64_decode($_COOKIE['data']), true); // use JSON for simple data
References
Tags
🤝 Adopt this term
£79/year · your link shown here
Added
15 Mar 2026
Edited
22 Mar 2026
Views
31
🤖 AI Guestbook educational data only
|
|
Last 30 days
Agents 0
No pings yet today
ChatGPT 6
Amazonbot 5
Perplexity 5
Google 4
Ahrefs 2
SEMrush 2
Qwen 1
Unknown AI 1
Also referenced
How they use it
crawler 25
crawler_json 1
Related categories
⚡
DEV INTEL
Tools & Severity
🔴 Critical
⚙ Fix effort: Medium
⚡ Quick Fix
Replace serialize()/unserialize() with json_encode()/json_decode() for data persistence — JSON is safer (no object instantiation), human-readable, and language-agnostic
📦 Applies To
PHP 5.0+
web
cli
queue-worker
🔗 Prerequisites
🔍 Detection Hints
serialize() data stored in database or cookie; unserialize() of any user-controlled or untrusted data; session data serialised as PHP objects
Auto-detectable:
✓ Yes
semgrep
psalm
phpstan
⚠ Related Problems
🤖 AI Agent
Confidence: Medium
False Positives: Medium
✗ Manual fix
Fix: High
Context: File
Tests: Update
CWE-502