Skip to Content
Course content

105: serialize and unserialize

Click on the "Edit" button in the top corner of the screen to edit your slide content.

I once spent three hours debugging a production issue where a user's settings were suddenly disappearing. The developer before me had stored a PHP array in a database column using serialize(). To "quickly" update a username in the database via a SQL query, they had manually edited the string. The result? The unserialize() call started returning false, and the application just wiped the user's preferences because it thought the data was missing.

The Mystery of the Vanishing Data

<?php
// Imagine this string was pulled from a database column
// It represents an array: ['username' => 'john']
$stored_data = 'a:1:{s:8:"username";s:4:"john";}';

$user_settings = unserialize($stored_data);
var_dump($user_settings); 
// Result: array(1) { ["username"]=> string(4) "john" }

// Now, imagine a developer manually edited the database to change "john" to "jonathan"
// but forgot to update the length prefix (s:4)
$corrupted_data = 'a:1:{s:8:"username";s:4:"jonathan";}';

$user_settings = unserialize($corrupted_data);
var_dump($user_settings); 
// Result: bool(false)
?>

If you run this, you'll notice that the second call doesn't throw a loud error; it just returns false. In a real app, a developer might write if (!$user_settings) { $user_settings = []; }, effectively deleting the user's data because of a single digit mistake in a string.

How PHP Tracks Serialized Strings

The reason this fails is that PHP's serialize() format isn't just a way to represent data; it's a strict map. Let's look at s:4:"john". The s stands for string, and the 4 tells PHP exactly how many bytes to read following the colon.

When PHP encountered s:4:"jonathan", it read exactly four characters ("jona") and then expected to find a closing quote. Instead, it found "than". This mismatch makes the entire string "malformed," and unserialize() gives up immediately. I've seen this happen countless times when people try to "hack" a database value without using the actual PHP functions.

Using Serialization the Right Way

To avoid this, you should never manually edit a serialized string. If you need to change a value, you must unserialize it, modify the resulting PHP variable, and then re-serialize it.

<?php
$data = 'a:1:{s:8:"username";s:4:"john";}';
$settings = unserialize($data);

// Modify the value using standard array logic
$settings['username'] = 'jonathan';

// Let PHP handle the length calculations
$updated_data = serialize($settings);
echo $updated_data; 
// Result: a:1:{s:8:"username";s:8:"jonathan";}
?>

Now the string is s:8:"jonathan", and PHP is happy. As a side note: if you find yourself needing to edit these values manually or share them with a JavaScript frontend, stop using serialize() and use json_encode() and json_decode() instead. JSON is a standard across languages and doesn't rely on these fragile length-prefixes. However, serialize() remains useful when you need to preserve specific PHP object types, which JSON cannot do.




📋 Practical Task

Building a User Preference Snapshot System

You are building a feature that allows users to "save" a snapshot of their current dashboard layout (which is stored as an associative array) so they can restore it later. This snapshot needs to be stored as a single string in a database.

Your Task:

  • Create an associative array called $dashboard_layout with at least three keys (e.g., 'theme', 'sidebar_collapsed', and 'widgets'—where widgets is itself a nested array of strings).
  • Use serialize() to convert this array into a string and store it in a variable called $db_snapshot.
  • Simulate a "restore" process: use unserialize() to convert $db_snapshot back into a PHP array.
  • Print the restored array to the screen using print_r() to verify that the structure (including the nested array) remained intact.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.