🛡️ PHP Security & Login
Estimated reading: 3 minutes 27 views

🧼 PHP Filtered Unserialize – Safely Deserialize User Data in PHP

Learn how to securely use unserialize() in PHP with filtering to prevent object injection and code execution vulnerabilities.


🧲 Introduction – Why Filtered Unserialize Matters

The unserialize() function in PHP is used to reconstruct a PHP value from a stored string representation — often for restoring sessions, caching, or structured data.

However, using unserialize() on untrusted user input is dangerous. Without filtering, it can lead to object injection, arbitrary code execution, or even remote code inclusion, especially if objects with magic methods (__wakeup, __destruct, etc.) are present.

🎯 In this guide, you’ll learn:

  • What filtered unserialization is
  • How to use unserialize() safely
  • Common attack vectors and how to prevent them
  • Best practices for handling serialized data in PHP

🧼 PHP Filtered Unserialize

unserialize(string $data, array $options = []): mixed

Starting from PHP 7.0, unserialize() supports an allowed_classes option that lets you control which classes can be unserialized.


🔐 Unsafe Usage (❌ Never Do This)

$data = $_POST['payload'];
$restored = unserialize($data); // ❌ Unsafe if data is user-controlled

📛 This can allow attackers to inject crafted object payloads leading to security exploits.


✅ Safe Usage with Filtering

$data = $_POST['payload'];
$restored = unserialize($data, ["allowed_classes" => false]);

✅ This blocks all objects from being unserialized — only arrays, strings, numbers, etc., will be restored


🧱 Allow Specific Classes Only

$data = $_POST['payload'];
$restored = unserialize($data, ["allowed_classes" => ["User", "Profile"]]);

✅ Only User and Profile objects will be allowed; all others are rejected


🧪 What Happens If Filtering Fails?

  • Disallowed classes are converted to __PHP_Incomplete_Class
  • PHP does not execute their constructors or destructors
  • Safer than allowing arbitrary deserialization

🛡️ Common Use Cases for Safe Unserialize

Use CaseRecommended Practice
Session or token recoveryUse filtering or avoid unserialize()
Configs, cachesPrefer json_encode() / json_decode()
Class data restorationAllow only specific classes
Form data deserializationSanitize and filter unserialized input

🔒 Best Practices for Serialized Data

  • ✅ Prefer json_encode() / json_decode() for non-object data
  • ✅ Use allowed_classes => false unless necessary
  • ✅ Never trust unserialized content from $_POST, $_GET, $_COOKIE, or third-party APIs
  • ✅ Avoid magic methods like __wakeup() and __destruct() in unserialized classes
  • ✅ Validate restored data before using it in business logic

🧾 Example of Filtered Unserialize in Action

// Serialized array of names
$data = serialize(['Alice', 'Bob', 'Charlie']);

// Simulate receiving it via POST
$_POST['names'] = $data;

// Safe unserialization (no objects allowed)
$names = unserialize($_POST['names'], ['allowed_classes' => false]);

print_r($names);

✅ Output:

Array
(
    [0] => Alice
    [1] => Bob
    [2] => Charlie
)

📌 Summary – Recap & Next Steps

unserialize() can be powerful — but also risky. Always filter input and restrict allowed classes to prevent object injection attacks. If you don’t need objects, stick to json_decode().

🔍 Key Takeaways:

  • Never unserialize untrusted user input without filtering
  • Use allowed_classes => false to block object injection
  • Whitelist only known, safe classes if object deserialization is required
  • Prefer json for structured non-object data

⚙️ Real-World Use Cases:
Safe form state restoration, caching configurations, session data decoding, object state recovery in private APIs


❓ Frequently Asked Questions (FAQs)

❓ What is object injection in PHP?
✅ It’s an attack where malicious serialized objects are injected and unserialized to execute magic methods.

❓ How do I check if a serialized string is safe?
✅ Use allowed_classes => false in unserialize() and validate the data manually after deserialization.

❓ Can I use unserialize() on session data?
⚠️ Only if you trust the session source. Use native session handling or encrypt custom session stores.

❓ Is unserialize() deprecated?
❌ No, but it’s discouraged in favor of safer alternatives like json_decode() for most use cases.

❓ Can unserializing cause remote code execution (RCE)?
✅ Yes, if deserialized objects include exploitable magic methods. That’s why filtering is critical.


Share Now :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

🧼 PHP Filtered Unserialize

Or Copy Link

CONTENTS
Scroll to Top