Skip to content
LatestPillow CVE-2026-112897 leaks heap memory via crafted TIFF images
Vulnerabilities

PHP Object Injection: Exploitation, Mitigation and Code Audit

Deserialisation of untrusted data allows attackers to execute arbitrary code by triggering magic methods during object reconstruction in PHP applications.

Illustration: A whiteboard displays a chaotic tangle of tangled red wires emerging from a single tangled knot.
AI-generated illustration: RedTeam Log
Quick answer

PHP object injection occurs when an application deserialises untrusted input without validation. Attackers craft serialised strings that trigger dangerous magic methods during reconstruction. You must validate input, use JSON for data exchange and implement strict whitelisting to prevent remote code execution through this vulnerability.

What is PHP object injection?

PHP object injection is a vulnerability that allows an attacker to manipulate the deserialisation process to execute arbitrary code. When PHP reconstructs an object from a serialised string, it invokes special methods known as magic methods. If an attacker controls the input data, they can craft a serialised string that forces the application to instantiate malicious objects. These objects can then perform actions such as deleting files, accessing databases or executing system commands. This attack does not require a traditional buffer overflow or logic error. It exploits the fundamental mechanism of how PHP handles object state restoration.

Infographic: PHP Object Injection: Exploitation, Mitigation and Code Audit. Magic methods like __wakeup execute automatically during deserialisation, creating hidden execution paths. Validating serialised data is difficult; converting to JSON prevents the object reconstruction attack surface. Legacy
Infographic: PHP Object Injection: Exploitation, Mitigation and Code Audit. Free to share with a link to RedTeam Log.

How does deserialisation enable code execution?

Deserialisation converts a stored representation of an object back into a live PHP object. During this process, PHP calls magic methods such as __wakeup or __destruct automatically. The __wakeup method prepares the object for use, while __destruct cleans up resources when the object is destroyed. An attacker creates a payload that instantiates a class containing a dangerous function call within one of these methods. When the application deserialises the payload, the magic method executes the hidden code. This happens before the application can validate the user's intent or permissions. The execution path is often invisible to standard input validation filters.

Which PHP functions are most vulnerable?

The primary function responsible for this vulnerability is unserialize(). Any code path that passes user-controlled data directly to unserialize() is at risk. This includes data submitted via HTTP POST requests, GET parameters, cookies and even HTTP headers. Secondary vulnerabilities arise when unserialize() is called indirectly. Functions like eval() or include() can become dangerous if they process data that has been previously deserialised or if they load files containing serialised objects. Developers must audit every instance of unserialize() in the codebase. They must also check for wrappers or helper functions that might call it behind the scenes.

What are PHP magic methods?

Magic methods are special functions in PHP that start with two underscores and are triggered by specific events. __construct runs when an object is created. __destruct runs when an object is destroyed. __wakeup runs after deserialisation. __toString converts an object to a string. __call handles calls to inaccessible methods. Attackers exploit these methods because they execute automatically without explicit invocation in the application logic. A class designed for benign purposes, such as logging or caching, can become dangerous if its magic methods interact with the filesystem or database. Understanding these methods is required for identifying potential exploitation chains.

Why is input validation difficult here?

Serialised PHP data is a complex string format that encodes type, length and property values. Validating this structure manually is error-prone and inefficient. Simple string sanitisation often fails because the malicious payload is embedded within valid-looking data. Regular expressions cannot reliably detect all possible object injection payloads. The complexity increases with nested objects and references. Attackers can obfuscate payloads using custom classes or by chaining multiple objects together. Relying on blacklisting known bad strings is ineffective because new class names and methods emerge constantly. The only reliable defence is to avoid deserialising untrusted data entirely.

Magic MethodTrigger EventRisk LevelTypical Abuse Case
__wakeupAfter deserialisationHighFile deletion, command execution
__destructObject destructionMediumDatabase cleanup bypass, log injection
__toStringString conversionLow-MediumSQL injection via string interpolation
__callInaccessible method callMediumPrivilege escalation via method spoofing
__setProperty assignmentLowData tampering, state manipulation

How do you fix existing code?

Refactoring code to remove unserialize() is the most effective remediation. Replace serialisation with JSON encoding for data exchange between components. If legacy code requires object state, implement a strict whitelist of allowed classes. This whitelist must be enforced at the deserialisation point using a custom unserialiser. You can use the Serializable interface or __serialize and __unserialize methods to control the process. Ensure that only trusted, internal objects can be reconstructed. For session data, consider using a database-backed session handler that stores data in a format that cannot be manipulated by users. Review related guides on insecure direct object references (IDOR) to ensure comprehensive data access controls.

What is the impact on managed services?

Managed service providers face significant risk when hosting PHP applications with object injection vulnerabilities. These vulnerabilities can lead to full server compromise, affecting multiple client environments. The impact extends beyond data theft to include denial of service and lateral movement within the network. Providers must implement strict isolation between customer accounts.

Regular vulnerability scanning for PHP deserialisation issues should be part of standard audits. You should also review emergency patching procedures to ensure rapid response to critical PHP updates. Monitoring for unusual process execution or file system changes can detect exploitation attempts. A robust software bill of materials (SBOM) helps track PHP versions and dependencies across the portfolio.

Are there automated detection tools?

Static application security testing (SAST) tools can identify calls to unserialize() in the source code. However, these tools often produce false positives when the function is used with trusted, internal data. Dynamic application security testing (DAST) tools may detect exploitation attempts but cannot confirm vulnerability without precise payloads. Manual code review remains the most reliable method for identifying complex exploitation chains. Developers should integrate security linting rules that flag unserialize() usage. These rules must require additional justification or mitigation strategies for each instance. Combining automated scanning with expert review provides the best balance of coverage and accuracy.

How does this relate to other injection flaws?

PHP object injection shares similarities with other injection vulnerabilities but operates on a different principle. Unlike SQL injection, which targets database queries, object injection targets the application's memory and execution context. It is distinct from NoSQL injection, which exploits query operators in document databases.

The impact can be similar to remote code execution flaws, but the mechanism is more subtle. Developers often overlook it because it requires specific class structures to exploit. Understanding the differences helps in prioritising remediation efforts. You should also consider hard-coded credentials as a secondary risk if the injected code accesses configuration files.

Key takeaways

  • Magic methods like __wakeup execute automatically during deserialisation, creating hidden execution paths.
  • Validating serialised data is difficult; converting to JSON prevents the object reconstruction attack surface.
  • Legacy code often relies on session data that remains vulnerable even with modern PHP versions.
Bottom line

PHP object injection exploits automatic method execution during deserialisation, making input validation unreliable. Replace `unserialize()` with JSON encoding and implement strict class whitelisting to eliminate the risk.

Frequently asked questions

Can PHP object injection occur in modern PHP versions?

Yes, the vulnerability exists in all PHP versions that support object serialisation. Newer versions may have additional safety features, but the core mechanism remains exploitable if untrusted data is deserialised.

Is JSON completely safe from injection attacks?

JSON is safe from object injection because it does not support object methods or automatic execution. However, JSON data can still be vulnerable to other attacks like cross-site scripting if not properly encoded.

How do I identify vulnerable classes in my codebase?

Search for classes that use magic methods like `__wakeup` or `__destruct` and interact with sensitive resources. Review how these classes are instantiated and whether user input can influence their properties.

Does HTTPS prevent PHP object injection?

No, HTTPS only encrypts data in transit. It does not protect against vulnerabilities in how the application processes deserialised data. The attack occurs on the server side after decryption.

How this guide was produced: written by the RedTeam Log editorial team with AI assistance, checked against the public references listed below, and reviewed when the facts change. See our editorial policy or report an error.

Further reading

  1. CISA Known Exploited Vulnerabilities Catalog
  2. National Vulnerability Database
  3. CVE Program
PHP object injectionphp securitydeserialisationobject injection

Related stories