Check if String Can be Unserialized in PHP

This tutorial will discuss how to check if string can be unserialized in PHP.

To check if a string can be unserialized in PHP, we can use the unserialize() function.

We pass the string as an argument to the function. If the function returns an unserialized value, it means that the given string can be successfully unserialized. If it returns false, it indicates that the given string cannot be unserialized.

We have created a separate function for this,

function isUnserializable($strValue)
{
    $result = false;
    try {
        $unserialized = unserialize($strValue);
        $result = ($unserialized !== false);
    } catch (Exception $e) {
    }
    return $result;
}

It accepts a string as an argument and returns true if the given string can be unserialized. The function utilizes the unserialize() function internally to perform the unserialization.

Please note that if the unserialize() function encounters any issues, such as invalid data or a malformed string, it may throw an exception or trigger an error. In such cases, it also means that the given string cannot be unserialized.

Let’s see the complete example,

<?php
/**
 * Check if a string can be unserialized.
 *
 * @param string $strValue The string to validate.
 * @return bool True if the string can be unserialized,
 *              false otherwise.
 */
function isUnserializable($strValue)
{
    $result = false;
    if (is_string($strValue)) {
        $unserialized = @unserialize($strValue);
        $result = ($unserialized !== false || $strValue === 'b:0;');
    }
    return $result;
}

// A string containing a serialized array
$strValue = 'a:2:{i:0;s:5:"delhi";i:1;s:6:"london";}';

if (isUnserializable($strValue)) {
    echo "The string can be unserialized.";
} else {
    echo "The string cannot be unserialized.";
}
?>

Output

The string can be unserialized.

Summary

Today, we learned how to check if string can be unserialized in PHP.

Leave a Comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top