Notice: unserialize(); Error at offset in Magento 2.2

Notice: unserialize(); Error at offset in Magento 2.2

In this article, I will show how we can solve unserialize error in Magento 2.

As per Magento 2.2 release note, Magento removes serialize/unserialize from most the code to improve protection against remote code execution attacks.

Magento 2.2 Release Note:

In general, we’ve removed serialize/unserialize from most the code to improve protection against remote code execution attacks. We’ve enhanced protection of code where use of object serialization or unserialization was unavoidable. Additionally, we’ve increased our use of output escaping to protect against cross-site scripting (XSS) attacks.

Magento 2.2 Release Note

We can use Magento\Framework\Serialize\SerializerInterface or \Magento\Framework\Serialize\Serializer\Json class to serialize and unserialize data.

protected $serialize;

public function __construct(
    ...
    \Magento\Framework\Serialize\SerializerInterface $serialize,
    ...
) {
    $this->serialize = $serialize;
}

Now use $this->serialize variable to serialize and unserialize data.

$this->serialize->serialize($data); // Serialize Data
$this->serialize->unserialize($data); // Unserialize Data