serialize / unserialize
serialize(mixed $value): string — unserialize(string $data, array $options = []): mixed
Turns any PHP value into a portable string and back. The core security lesson: unserialize on untrusted input is object injection (triggering __wakeup/__destruct attack chains) - the allowed_classes whitelist is the only safe usage.
C C23
#include <stdio.h>
typedef struct {
int a;
double b;
int c;
} Data;
/* C has no serialization: hand-rolled fixed text format */
static int serialize(const Data *d, char *out) {
return sprintf(out, "%d %g %d", d->a, d->b, d->c);
}
static Data unserialize(const char *in) {
Data d = {0, 0.0, 0}; /* zero-init before parse: no garbage on failure */
sscanf(in, "%d %lf %d", &d.a, &d.b, &d.c);
return d;
}
int main(void) {
Data d = {1, 2.5, 1};
char buf[64] = {0};
serialize(&d, buf);
printf("%s\n", buf);
Data r = unserialize(buf);
printf("%d %g %d\n", r.a, r.b, r.c);
return 0;
}
1 2.5 1 1 2.5 1
C++ C++26
#include <iostream>
#include <sstream>
struct Data {
int a = 1;
double b = 2.5;
int c = 1;
};
// No reflection in C++: the standard library cannot serialize a struct,
// so hand-rolled text format via iostream is the classic teaching demo
static std::string serialize(const Data &d) {
std::ostringstream out;
out << d.a << ' ' << d.b << ' ' << d.c;
return out.str();
}
int main() {
Data d;
std::string s = serialize(d);
std::cout << s << "\n";
std::istringstream in(s);
Data r;
in >> r.a >> r.b >> r.c;
std::cout << r.a << ' ' << r.b << ' ' << r.c << "\n";
}
1 2.5 1 1 2.5 1
C# v11.0.100
using System.Text.Json;
// The unserialize slot in .NET history belongs to BinaryFormatter: object
// injection made it the legacy serializer - Microsoft deprecated it in 2019
// and REMOVED it in .NET 9, a complete deprecation-to-removal arc.
// The modern replacements are data-only formats:
var data = new Data();
string s = JsonSerializer.Serialize(data);
Console.WriteLine(s);
var restored = JsonSerializer.Deserialize<Data>(s)!;
Console.WriteLine(restored.A == 1 && restored.B == 2.5 && restored.C);
class Data {
public int A { get; set; } = 1;
public double B { get; set; } = 2.5;
public bool C { get; set; } = true;
}
{"A":1,"B":2.5,"C":true}
True
Go v1.27.4
package main
import (
"bytes"
"encoding/gob"
"fmt"
)
type Demo struct {
A int
B float64
C bool
}
func main() {
// Go's binary serializer is gob: schema-carrying, self-describing
// wire format, but Go-to-Go only
var buf bytes.Buffer
if err := gob.NewEncoder(&buf).Encode(Demo{A: 1, B: 2.5, C: true}); err != nil {
return
}
var got Demo
if err := gob.NewDecoder(&buf).Decode(&got); err != nil {
return
}
fmt.Println(got.A, got.B, got.C)
// gob decodes into pre-declared structs: wire bytes never instantiate
// unknown types, so the PHP object-injection class has no analog here
}
1 2.5 true
Java v27.0.1
import java.io.*;
public class Main {
// Serializable + readObject is Java's unserialize - and its danger:
// readObject invokes hooks on every class found in the stream, so
// crafted bytes trigger arbitrary code (the "gadget chain" problem -
// the biggest recurring security theme in Java's history)
public static class Demo implements Serializable {
int a = 1;
}
public static void main(String[] args) throws Exception {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try (ObjectOutputStream out = new ObjectOutputStream(bos)) {
out.writeObject(new Demo());
}
try (ObjectInputStream in = new ObjectInputStream(
new ByteArrayInputStream(bos.toByteArray()))) {
Demo d = (Demo) in.readObject();
System.out.println(d.a);
}
}
}
1
JavaScript v26.13.1
const data = { a: 1, b: 2.5, c: true };
// JSON is the serialize/unserialize of JS: parse cannot execute code,
// so the object-injection attack class does not exist here.
const s = JSON.stringify(data);
console.log(s);
const restored = JSON.parse(s);
console.log(JSON.stringify(restored) === s); // round trip
// the price: JSON carries plain data only - no Date, Map, Set or class
// instances (they become {} or throw), and no cyclic references
{"a":1,"b":2.5,"c":true}
true
PHP v8.6.0
// serialize: any PHP value -> a portable string; unserialize restores it
$data = ['a' => 1, 'b' => 2.5, 'c' => true];
$s = serialize($data);
echo $s, "\n";
var_dump(unserialize($s) === $data); // round trip: equal value
// THE security lesson: unserialize() on untrusted input is object injection.
// Crafted payloads instantiate arbitrary classes and trigger __wakeup/
// __destruct magic methods - the classic PHP gadget chain. The whitelist
// option allowed_classes is the only safe way to touch untrusted bytes:
class Demo { public $v = 1; }
$obj = unserialize(serialize(new Demo()), ['allowed_classes' => false]);
var_dump(get_class($obj)); // the class was NOT instantiated: incomplete shell
var_dump(is_object($obj)); // still an object - but of no real class
a:3:{s:1:"a";i:1;s:1:"b";d:2.5;s:1:"c";b:1;}
bool(true)
string(22) "__PHP_Incomplete_Class"
bool(true)
Python v3.15.2
import json
import pickle
data = {"a": 1, "b": 2.5, "c": True}
# pickle is unserialize's equally dangerous twin: loading crafted bytes
# can execute arbitrary code. The official docs warn - never unpickle
# data that comes from an untrusted source.
s = pickle.dumps(data)
print(pickle.loads(s) == data) # round trip
# for data exchange use JSON: no code execution, plain data only
print(json.dumps(data))
True
{"a": 1, "b": 2.5, "c": true}
Rust v1.99.1
use serde_json::{json, Value};
fn main() {
// serde_json is data-only by design: deserializing JSON never
// instantiates user types or runs code - the type system keeps the
// deserialize step inert until you map it onto your own structs
let data = json!({"a": 1, "b": 2.5, "c": true});
let s = serde_json::to_string(&data).unwrap();
println!("{}", s);
let restored: Value = serde_json::from_str(&s).unwrap();
println!("{}", restored == data);
}
{"a":1,"b":2.5,"c":true}
true
TypeScript v26.13.1
const data = { a: 1, b: 2.5, c: true };
// JSON is the serialize/unserialize of TS: parse cannot execute code,
// so the object-injection attack class does not exist here.
const s = JSON.stringify(data);
console.log(s);
const restored = JSON.parse(s) as typeof data;
console.log(JSON.stringify(restored) === s); // round trip
// the price: JSON carries plain data only - no Date, Map, Set or class
// instances (they become {} or throw), and no cyclic references
{"a":1,"b":2.5,"c":true}
true
Language differences
C: no standard serialization; the example hand-rolls a fixed text format (sprintf/sscanf round trip). Custom binary protocols mean defining endianness, alignment and versioning yourself - "trusting bytes as a struct directly" is exactly where every serialization security problem begins.
C++: same as C - without reflection the standard library cannot serialize a struct, and an iostream text round trip is the classic teaching demo; real projects reach for third parties (Boost.Serialization, protobuf, cereal).
C#: BinaryFormatter was unserialize's historical counterpart - its object injection made it notorious: Microsoft deprecated it in 2019 and REMOVED it in .NET 9 (a complete deprecation-to-removal arc). Modern replacements are data-only formats like System.Text.Json.
Go: encoding/gob carries its own schema and a self-describing wire format, but is Go-to-Go only; decoding targets a pre-declared struct - wire bytes never instantiate unknown types, so the PHP object-injection class has no direct analog here.
Java: Serializable + readObject is unserialize's counterpart and Java's biggest security theme: readObject invokes hooks on every class in the stream, so crafted payloads trigger arbitrary code (deserialization gadget chains - the root of the Commons-Collections family of vulnerabilities). Defense is ObjectInputFilter whitelisting.
JavaScript: JSON.stringify/parse is limited but safe - parse executes no code, so the object-injection attack class does not exist; the price is plain data only (Dates become strings, Map/Set/class instances are lost, cyclic references unsupported).
PHP: unserialize on untrusted input IS object injection: crafted payloads instantiate arbitrary classes and trigger __wakeup/__destruct and other magic methods (POP-chain vulnerabilities). Three defenses: never accept user-controlled serialized strings, the allowed_classes whitelist (false or an array of class names), and JSON where possible.
Python: pickle is unserialize's equally dangerous twin - loading crafted bytes executes arbitrary code, and the official docs clearly warn to never unpickle data from an untrusted source; use JSON for data exchange.
Rust: the serde ecosystem is data-only by default - deserializing JSON never instantiates user types or runs code; serde stays inert until you explicitly map it onto your own structs, and the type system cuts injection attacks off at the root.
TypeScript: same as JavaScript.