PHP – Check If a String Can Be Unserialized or not

This post shows you how to check if a string can be unserialized or not in PHP.

 

1. Implementation

Here is the function, if it returns true, the string can be serialized and vice versa.

function canBeUnserialized($string) {
    if (@unserialize($string) === false) {
        return false;
    }
    return true;
}

 

2. Example

example.php
<?php

function canBeUnserialized($string) {
    if (@unserialize($string) === false) {
        return false;
    }
    return true;
}

// Example 1.
// serialized string
$string1 = 'O:7:"Student":3:{s:4:"name";s:5:"Maria";s:3:"age";s:2:"18";s:6:"gender";s:6:"female";}';

if (canBeUnserialized($string1)) {
    echo 'This string 1 can be serialized.';
    $object = unserialize($string1);
    echo '<pre>';
    var_dump($object);
    echo '</pre>';
} else {
    echo 'Can not unserialize string 1.';
}


// Example 2.
// a broken serialized string
$string2 = 'O:7:"Student":3:{s:4:"name";s:5:';

if (canBeUnserialized($string2)) {
    echo 'This string 2 can be serialized.';
    $object = unserialize($string2);
    echo '<pre>';
    var_dump($object);
    echo '</pre>';
} else {
    echo 'Can not unserialize string 2.';
}

Result:

This string 1 can be serialized.
object(__PHP_Incomplete_Class)#1 (4) {
  ["__PHP_Incomplete_Class_Name"]=>
  string(7) "Student"
  ["name"]=>
  string(5) "Maria"
  ["age"]=>
  string(2) "18"
  ["gender"]=>
  string(6) "female"
}

Can not unserialize string 2.

Leave a Reply

avatar