How to Serialize and Unserialize PHP Objects in Node.js (with Base64 Encoding)
Migrating a legacy application from PHP to Node.js often comes with a major hurdle: data compatibility. One of the most common friction points is dealing with database columns populated using PHP's native serialize() and base64_encode() functions.
If your database contains thousands of records formatted like this, rewriting the database overnight isn't always practical. You need a reliable way in Node.js to read, modify, and serialize objects back into the exact same Base64-encoded PHP serialization format. In this guide, we will walk through how to handle this two-way process seamlessly.
The Core Problem
In PHP, serializing an array or object to Base64 looks like this:
$stored_data = base64_encode(serialize($options));
To achieve the exact inverse and reverse processes in Node.js, you need two things:
- A reliable parser that mimics PHP's custom serialization protocol.
- Node.js built-in
Buffermethods to handle Base64 decoding and encoding.
Recommended Library: php-serialize
The npm package php-serialize is the standard tool for handling PHP-style serialization in Node.js. It supports nested arrays, objects, booleans, integers, strings, and null values.
Install it using npm:
npm install php-serialize
Step-by-Step Implementation
1. Reading and Unserializing Base64 Data
When fetching the string from the database, convert the Base64 string into a readable UTF-8 string or buffer, then pass it to unserialize():
const { serialize, unserialize } = require('php-serialize');
// Sample string retrieved from the database
const base64FromDb = 'YTo2OntzOjExOiJkaXNwbGF5X2NhbSI7czoxOiIxIjtzOjEyOiJlbmFibGVfc291bmQiO3M6MToiMSI7czoxMToiZW5hYmxlX2VmZmUiO3M6MToiMSI7czoxMToic2hvd19teV9jYW0iO3M6MToiMSI7czoxMToib3Blbl9teV9jYW0iO3M6MToiMCI7czoxOToid2ViY2FtX25vcGVybWlzc2lvbiI7czoxOiIxIjt9';
// Step 1: Decode from Base64 to string
const serializedString = Buffer.from(base64FromDb, 'base64').toString('utf8');
// Step 2: Unserialize into a JavaScript object
const options = unserialize(serializedString);
console.log(options);
/*
Output:
{
display_cam: '1',
enable_sound: '1',
enable_effe: '1',
show_my_cam: '1',
open_my_cam: '0',
webcam_nopermission: '1'
}
*/
2. Modifying the Data
Once you have a standard JavaScript object, mutate the properties as required by your business logic:
// Modify values as needed
options.display_cam = '0';
options.open_my_cam = '1';
3. Reserializing and Encoding to Base64
To write the updated object back to your database in the exact format PHP expects, serialize the JavaScript object back to PHP format, and use Buffer.from() with .toString('base64'):
// Step 1: Serialize the JavaScript object back into PHP format
const serializedUpdated = serialize(options);
// Step 2: Encode to Base64
const base64ToStore = Buffer.from(serializedUpdated, 'utf8').toString('base64');
console.log(base64ToStore);
// Ready to be executed in an SQL UPDATE statement
Putting It Together in Helper Functions
To keep your codebase clean and readable, bundle this logic into clean utility functions:
const { serialize, unserialize } = require('php-serialize');
const phpBase64 = {
decode(encodedString) {
if (!encodedString) return null;
const decoded = Buffer.from(encodedString, 'base64').toString('utf8');
return unserialize(decoded);
},
encode(dataObject) {
const serialized = serialize(dataObject);
return Buffer.from(serialized, 'utf8').toString('base64');
}
};
// Usage:
const record = phpBase64.decode(row.options);
record.display_cam = '0';
row.options = phpBase64.encode(record);
Key Considerations and Best Practices
- String Lengths Matter: PHP's serialization stores byte counts (e.g.,
s:11:"display_cam"). Always make sure your serialization tool properly handles multi-byte UTF-8 characters if you work with non-ASCII text. - Long-Term Migration Plan: While supporting legacy PHP serialization allows for zero-downtime migrations, storing serialized PHP structures or Base64 blobs impairs querying performance inside databases like MySQL/PostgreSQL. Plan an incremental migration to native
JSONdatabase types over time.