Check to see if a string is serialized?

Check to see if a string is serialized?

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

Check to see if a string is serialized?

Determining whether a string in PHP is the result of serialize() requires understanding the binary structure of the data format itself, rather than relying on a simple magic number or a single boolean flag exposed by the core engine. The serialization format is a custom binary protocol designed for efficient storage and retrieval, but it does not include an explicit header that states "this is serialized data." Consequently, any function attempting to validate this must inspect the byte-level representation of the string.

The most reliable method involves checking the first few bytes of the string against known opcodes defined in the PHP internal implementation. When serialize() runs, it prepends a specific set of bytes that indicate the type of data being stored. For instance, an integer will start with \x00, while a string begins with \x05. If you attempt to deserialize a malformed string or one that was not created by serialize(), PHP's unserialize() function will throw an exception. However, relying solely on exceptions to detect the format is inefficient and throws errors during normal operation where you simply need to know the type of data present.

A robust approach utilizes bitwise operations on the first byte to identify the opcode. You can create a helper function that checks the first character of the string. If the string is empty, it cannot be serialized data. If it contains characters, you extract the ASCII value of the first byte using ord(). This value corresponds directly to an opcode defined in the PHP source code (specifically within the Zend engine).

Here is a practical implementation that checks the first byte without triggering exceptions:

function isSerialized(string $data): bool {
    if ($data === '') {
        return false;
    }

    $firstByte = ord($data[0]);

    // These are the known starting opcodes for standard serialization.
    // 0x00 = integer, 0x05 = string, 0x08 = array (old style), 
    // 0x09 = array (new style), etc.
    $knownOpcodes = [0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09];

    return in_array($firstByte, $knownOpcodes, true);
}

This logic works because the serialization format is strictly binary. A string containing JSON data, for example, would typically start with { or [, which have ASCII values of 123 and 91 respectively. These values are not in the $knownOpcodes list, causing the function to correctly return false. Similarly, a standard PHP variable dumped via var_dump() starts with the string "string:" or "bool:", neither of which aligns with the binary opcodes.

Why Not Just Try Unserializing?

The obvious alternative is attempting to run unserialize($data) and catching an exception if it fails. While this confirms that a string is serialized if it succeeds, it carries significant overhead. Throwing exceptions is expensive in terms of CPU cycles and memory allocation compared to a simple bitwise check. Furthermore, unserialize() can be exploited in certain contexts if the application handles untrusted input without strict validation, potentially leading to deserialization vulnerabilities if code is executed during the process (though modern PHP mitigates many of these risks). Using the opcode check allows you to validate the format before attempting any costly parsing operations.

Version Compatibility and Edge Cases

One must be cautious regarding PHP version compatibility. The serialization format has evolved. In older versions of PHP, arrays were serialized differently than in newer versions, resulting in different opcodes (0x08 vs 0x09). While the code above includes a range of common opcodes to cover both styles, relying on a static list might miss edge cases introduced by future opcode changes or specific internal types like NULL which uses 0x07.

Additionally, this method assumes standard serialization. If you are dealing with custom serializers or libraries that mimic the binary format but introduce their own headers or checksums, this simple byte-check will yield false positives. The PHP manual provides documentation on the format at https://www.php.net/manual/en/function.serialize, but note that the exact implementation details of opcodes are internal to the Zend Engine and not part of the public API contract.

Conclusion

Checking for serialized data is fundamentally a binary inspection task. By examining the first byte against the known set of opcodes, you can efficiently distinguish between raw PHP variables, JSON strings, and actual serialize() output without incurring the performance penalty of exception handling. This approach offers a lightweight gatekeeper for applications that need to handle mixed input streams or perform safe data migration.

Our network