Unsafe deserialization allows hostile input to create or manipulate objects and may trigger gadget chains.
What It Does
Unsafe deserialization allows hostile input to create or manipulate objects and may trigger gadget chains. The following examples distinguish a normal use case, a boundary case and a practical application.
Requirements and Compatibility
PHP 8.x and a local test environment. Apply input validation, correct error handling and the requirements of any optional libraries.
The code focuses on the core concept. Production implementation may also need routes, validation, persistence, authorization or deployment tooling.
Example 1: Basic Behavior
Understand the primary operation and its inputs.
<?php
$payload = '{"id":8,"active":true}';
$data = json_decode($payload, true, 32, JSON_THROW_ON_ERROR);
if (!is_int($data['id'] ?? null)) throw new UnexpectedValueException('Invalid ID');
echo $data['id'];
Example 2: Another Case
Check failure behavior or a different execution path.
<?php
$malicious = 'O:8:"stdClass":0:{}';
$result = @unserialize($malicious, ['allowed_classes' => false]);
var_dump($result instanceof __PHP_Incomplete_Class); // Still avoid untrusted PHP serialization
Practical Example: Putting It to Use
Replace untrusted object serialization with constrained structured input.
<?php
$json = '{"type":"invoice","amount":850}';
$data = json_decode($json, true, 16, JSON_THROW_ON_ERROR);
if (($data['type'] ?? '') !== 'invoice' || !is_int($data['amount'] ?? null)) throw new UnexpectedValueException('Invalid record');
echo $data['amount'];
Important Behavior and Edge Cases
Restrict serialization to trusted internal data and migrate public payloads to validated JSON.
Comparison with Related Functions or Approaches
| Option | What it means in practice |
|---|---|
| Avoiding Unsafe Deserialization | Unsafe deserialization allows hostile input to create or manipulate objects and may trigger gadget chains. |
| Related approach | Use typed DTO constructors after decoding structured data. |
Common Beginner Mistakes
| Mistake | Correct approach |
|---|---|
| Ignoring the important boundary for Avoiding Unsafe Deserialization | Restrict serialization to trusted internal data and migrate public payloads to validated JSON. |
| Assuming a related mechanism has the same behavior | Use typed DTO constructors after decoding structured data. |
Key Takeaways
- Unsafe deserialization allows hostile input to create or manipulate objects and may trigger gadget chains.
- Restrict serialization to trusted internal data and migrate public payloads to validated JSON.
- Use typed DTO constructors after decoding structured data.
Before adapting these examples, verify the return values, test the failure paths and confirm that your application meets its security and environment requirements.