Serialize objects
Storing a value means turning it into text and reading it back later. PHP has two formats for that, the native serialize() form and JSON, and the difference between them is also the difference between trusted and untrusted input.
serialize()
The serialize function turns a value into a storable string. A file or cache cell can hold the string until you need the value again.
The unserialize function rebuilds the value from that string. Both calls below work on plain data with no objects involved.
<?php $data = ["a" => 1, "b" => 2]; $text = serialize($data); echo $text, PHP_EOL; $back = unserialize($text); echo array_sum($back), PHP_EOL; echo $back["b"], PHP_EOL;
php serialize.php
a:2:{s:1:"a";i:1;s:1:"b";i:2;}
3
2
The string names the type and the length of every part, which is why a shorter or longer value cannot be read as something else. Both reads work on the array that came back.
__serialize
The __serialize method returns the array that serialize stores, and __unserialize restores state from it. The pair shapes exactly what leaves the object.
Skip handles and secrets in that array. Stored data should hold facts, not live resources.
<?php class Token { public string $id = "abc"; public string $secret = "hunter2"; public function __serialize(): array { return ["id" => $this->id]; } public function __unserialize(array $data): void { $this->id = $data["id"]; } } $t = new Token(); $t->id = "xyz"; $text = serialize($t); echo $text, PHP_EOL; echo str_contains($text, "hunter2") ? "secret stored" : "secret not stored", PHP_EOL; echo unserialize($text)->id, PHP_EOL;
php custom.php
O:5:"Token":1:{s:2:"id";s:3:"xyz";}
secret not stored
xyz
The string holds one field, so the secret never reaches the file, and the rebuilt object restores exactly the id that was stored.
JsonSerializable
The json_encode function calls jsonSerialize when the object uses the interface. The method returns plain arrays and scalars.
Any client can read that output, which makes JSON the default for APIs and logs.
<?php class User implements JsonSerializable { public function __construct(public string $name) { } public function jsonSerialize(): mixed { return ["name" => $this->name]; } } echo json_encode(new User("Ann")), PHP_EOL; $plain = new stdClass(); $plain->name = "Ann"; echo json_encode($plain), PHP_EOL;
php json.php
{"name":"Ann"}
{"name":"Ann"}
The method decided the shape of the first object, and the plain object produced the same JSON because its properties were already public strings.
Never unserialize input
Never pass request data to unserialize. The format can build objects and reach code paths you did not plan.
Decode JSON for input instead. Plain arrays carry the same facts with none of the object risk.
<?php $body = '{"name":"Ann"}'; $data = json_decode($body, true); echo $data["name"], PHP_EOL; echo json_last_error_msg(), PHP_EOL;
php input.php
Ann
No error
The second argument true turns the JSON object into a plain array, and the error message says the decode was clean.
Exercises
- Serialize a nested array, print the string and rebuild it.
- Add a second field to __serialize() and watch the string change.
- Give an object a jsonSerialize() that hides one property and print the JSON.
- Decode a broken JSON string with json_decode() and print the message of json_last_error_msg().
- Explain why unserializing a value from a cookie is dangerous.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does
serialize()produce?Answer
A string that can be stored and read back
The native format writes the type and content of every part into one string.
-
What does
__serialize()return?Answer
An array of the fields that are stored
The method describes the state as an array, and PHP writes that array into the string.
-
Which method restores the state of an object from that array?
Answer
__unserialize()
PHP calls __unserialize() with the stored array and the method writes the fields back.
-
Why should request data never go to
unserialize()?Answer
It can create objects and reach code paths the request did not plan
The format names classes, so attacker-controlled text can build objects and trigger their methods.
-
What does this program print?
<?php $data = ["a" => 1, "b" => 2]; echo serialize($data);Answer
a:2:{s:1:"a";i:1;s:1:"b";i:2;}
The native format lists the count and then every key with its type and value.
-
What does this program print?
<?php $data = ["a" => 1, "b" => 2]; $back = unserialize(serialize($data)); echo array_sum($back);Answer
3
The round trip returns the same two integers, and their sum is 3.
-
What does this program print?
<?php class Token { public string $id = "abc"; public string $secret = "hunter2"; public function __serialize(): array { return ["id" => $this->id]; } } $t = new Token(); echo serialize($t);Answer
O:5:"Token":1:{s:2:"id";s:3:"abc";}
Only the array from __serialize() is stored, so the secret is not in the string.
-
What does this program print?
<?php class User implements JsonSerializable { public function __construct(public string $name) { } public function jsonSerialize(): mixed { return ["name" => $this->name]; } } echo json_encode(new User("Ann"));Answer
{"name":"Ann"}
json_encode() calls jsonSerialize() and writes the array it returns.
-
What does the second argument
trueofjson_decode($body, true)do?Answer
It returns associative arrays instead of objects
Without the flag the decoded object is a stdClass; with it every object becomes an array.
-
Which format should carry data that comes from a user?
Answer
JSON, decoded into plain arrays
JSON names no classes, so decoding it cannot build objects or call their methods.
The code on this page was run with PHP 8.5.13 (php -v) in Alpine Linux, with the commands shown above.
Article author: Arthur Isaev