PHP unserialize

Summary: in this tutorial, you’ll learn how to use the PHP unserialize() function to convert a serialized string into an object.

Introduction to the PHP unserialize() function

The unserialize() function converts a serialized string into an object. Here’s the syntax of the unserialized() function:

unserialize(string $data, array $options = []): mixedCode language: PHP (php)

The unserialized() function accepts two parameters:

  • $data is the serialized string.
  • $options is an associative array that contains the options for converting the serialized string into the object.

If the unserialize() function cannot convert the serialized string ($data) into an object, it returns false with an E_NOTICE.

Notice that the unserialize() function also returns false if the unserialized string is serialized from the false value.

PHP unserialize() function example

First, define a Customer class that has three properties id, name, and email:

<?php

class Customer
{

    public function __construct(
        private int $id,
        private string $name,
        private string $email
    ) {
    }

    public function getInitial()
    {
        if ($this->name !== '') {
            return strtoupper(substr($this->name, 0, 1));
        }
    }
}Code language: PHP (php)

Second, use the serialize() function to serialize a Customer object into a string and save it into the customer.dat file:

<?php

require 'Customer.php';

$customer = new Customer(10, 'John Doe', '[email protected]');
$str = serialize($customer);

file_put_contents('customer.dat', $str);Code language: PHP (php)

Third, use the unserialize() function to convert the serialized string into a Customer object.

<?php

require 'Customer.php';

$str = file_get_contents('customer.dat');
$customer = unserialize($str);

var_dump($customer);Code language: PHP (php)

Output:

object(Customer)#1 (3) {
    ["id":"Customer":private]=> int(10)
    ["name":"Customer":private]=> string(8) "John Doe"
    ["email":"Customer":private]=> string(20) "[email protected]"
}Code language: PHP (php)

When unserializing an object, if the class of the object is not known, the unserialize() function will create an object of the __PHP_Incomplete_Class class instead.

For example, if you remove the require construct in the above example as follows:

<?php

$str = file_get_contents('customer.txt');
$customer = unserialize($str);

var_dump($customer);Code language: PHP (php)

You’ll get an object of the PHP_Incomplete_Class class. The output will look like this:

object(**PHP_Incomplete_Class)#1 (4) {
    ["**PHP_Incomplete_Class_Name"]=> string(8) "Customer"
    ["id":"Customer":private]=> int(10)
    ["name":"Customer":private]=> string(8) "John Doe"
    ["email":"Customer":private]=> string(20) "[email protected]"
}Code language: PHP (php)

The unserialize() function creates a completely new object that does not reference the original object. For example:

<?php

require 'Customer.php';

// serialize the customer object
$customer1 = new Customer(10, 'John Doe', '[email protected]');
$str = serialize($customer1);
file_put_contents('customer.txt', $str);

// unserialize it
$str = file_get_contents('customer.txt');
$customer2 = unserialize($str);

// these object are not the same
var_dump($customer1 === $customer2); // falseCode language: PHP (php)

The __unserialize() magic method

The unserialize() function checks if the object has the __unserialize() method. If so, it’ll call the __unserialize() method to restore the object’s state. Consider the following example.

First, define a FileReader class:

<?php

class FileReader
{


    private $filehandle;

    private $filename;


    public function __construct(string $filename)
    {
        $this->filename = $filename;
        $this->open();
    }

    private function open()

    {
        $this->filehandle = fopen($this->filename, 'r');

        return $this;
    }

    public function read()
    {
        $contents = fread($this->filehandle, filesize($this->filename));

        return nl2br($contents);
    }

    public function close()
    {
        if ($this->filehandle) {
            fclose($this->filehandle);
        }
    }


    public function __sleep(): array
    {
        $this->close();

        return array('filename');
    }

    public function __unserialize(): void
    {
        $this->open();
    }
}Code language: PHP (php)

In the FileReader class, the __unserialize() method re-opens the file once the FileReader object is unserialized.

Second, serialize a FileReader object, save it into the objects.dat file, and unserialize it:

<?php


require 'FileReader.php';

$filename = 'objects.dat';


// serialize the $fileReader
file_put_contents(
    $filename,
    serialize(new FileReader('readme.txt'))
);

// unserialized the file reader
$file_reader = unserialize(file_get_contents($filename));

echo $file_reader->read();

$file_reader->close();Code language: PHP (php)

The __wakeup() magic method

Similar to the __unserialize() method, the unserialize() function also checks for the existence of the __wakeup() method of the unserialized object.

If present, the unserialize() function will call the __wakeup() method to reconstruct the state that the object may have.

In practice, you can perform reinitialization tasks in the __wakeup() method, such as reopening the file or re-connecting to the database.

If an object has both __unserialize() and __wakup() methods, the unserialize() will call __unserialize() method only and ignore the __wakup() method.

Summary

  • Use the unserialize() method to convert a serialized string into an object.
  • The unserialize() method calls the __unserialize() or __wakeup() method of the object to perform re-initialization tasks.
  • The unserialize() method calls the __unserialize() method only if an object has both __unserialize() and __wakeup() methods.
Did you find this tutorial useful?