session_decode / session_encode
session_decode(string $data): bool — session_encode(): string|false
Session-data (de)serialization: session_encode serializes $_SESSION into the internal format string (with the default handler, key names joined to serialize-encoded values by |), session_decode decodes and repopulates $_SESSION; decoding untrusted input is the same injection surface as unserialize.
C C23
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* vendor cJSON stands in for the serialization round trip */
#include "cJSON.h"
int main(void) {
cJSON *data = cJSON_CreateObject();
cJSON_AddStringToObject(data, "user", "alice");
cJSON_AddNumberToObject(data, "visits", 3);
char *encoded = cJSON_PrintUnformatted(data);
printf("encoded: %s\n", encoded);
cJSON *restored = cJSON_Parse(encoded);
printf("user: %s\n", cJSON_GetStringValue(cJSON_GetObjectItem(restored, "user")));
printf("visits: %d\n", (int)cJSON_GetNumberValue(cJSON_GetObjectItem(restored, "visits")));
char *again = cJSON_PrintUnformatted(restored);
printf("round trip: %s\n", strcmp(encoded, again) == 0 ? "true" : "false");
free(encoded); free(again);
cJSON_Delete(data); cJSON_Delete(restored);
return 0;
}
encoded: {"user":"alice","visits":3}
user: alice
visits: 3
round trip: true
C++ C++26
#include <iostream>
#include "nlohmann/json.hpp"
int main() {
// nlohmann/json is the de-facto serialization round trip (keys sorted alphabetically on dump)
const nlohmann::json data = {{"user", "alice"}, {"visits", 3}};
const std::string encoded = data.dump();
std::cout << "encoded: " << encoded << "\n";
const nlohmann::json restored = nlohmann::json::parse(encoded);
std::cout << "user: " << restored["user"].get<std::string>() << "\n";
std::cout << "visits: " << restored["visits"].get<int>() << "\n";
std::cout << "round trip: " << (restored == data ? "true" : "false") << "\n";
return 0;
}
encoded: {"user":"alice","visits":3}
user: alice
visits: 3
round trip: true
C# v11.0.100
using System.Text.Json;
// SessionData declared at the bottom (top-level statements take the file head)
var data = new SessionData { User = "alice", Visits = 3 };
var options = new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase };
string encoded = JsonSerializer.Serialize(data, options);
Console.WriteLine("encoded: " + encoded);
var restored = JsonSerializer.Deserialize<SessionData>(encoded, options)!;
Console.WriteLine("user: " + restored.User);
Console.WriteLine("visits: " + restored.Visits);
Console.WriteLine("round trip: " + (JsonSerializer.Serialize(restored, options) == encoded));
public class SessionData
{
public string User { get; set; } = "";
public int Visits { get; set; }
}
encoded: {"user":"alice","visits":3}
user: alice
visits: 3
round trip: True
Go v1.27.4
package main
import (
"encoding/json"
"fmt"
)
// session payload struct: field order maps to PHP's key order in the encoded string
type SessionData struct {
User string `json:"user"`
Visits int `json:"visits"`
}
func main() {
// encoding/json is the serialization round trip (fields in declaration order)
data := SessionData{User: "alice", Visits: 3}
encoded, _ := json.Marshal(data)
fmt.Println("encoded:", string(encoded))
var restored SessionData
json.Unmarshal(encoded, &restored)
fmt.Println("user:", restored.User)
fmt.Println("visits:", restored.Visits)
back, _ := json.Marshal(restored)
fmt.Println("round trip:", string(back) == string(encoded))
}
encoded: {"user":"alice","visits":3}
user: alice
visits: 3
round trip: true
Java v27.0.1
import org.json.JSONObject;
public class Main {
public static void main(String[] args) {
// org.json is the stdlib-adjacent JSON round trip (backed by a HashMap, so key order is its own)
JSONObject data = new JSONObject().put("user", "alice").put("visits", 3);
String encoded = data.toString();
System.out.println("encoded: " + encoded);
JSONObject restored = new JSONObject(encoded);
System.out.println("user: " + restored.getString("user"));
System.out.println("visits: " + restored.getInt("visits"));
System.out.println("round trip: " + restored.toString().equals(encoded));
}
}
encoded: {"visits":3,"user":"alice"}
user: alice
visits: 3
round trip: true
JavaScript v26.13.1
// JSON.stringify/parse is the language-level round trip; framework session stores
// serialize with their own codecs (JSON, MessagePack, protobuf)
const data = { user: "alice", visits: 3 };
const encoded = JSON.stringify(data);
console.log("encoded:", encoded);
const restored = JSON.parse(encoded);
console.log("user:", restored.user);
console.log("visits:", restored.visits);
console.log("round trip:", JSON.stringify(restored) === encoded);
encoded: {"user":"alice","visits":3}
user: alice
visits: 3
round trip: true
PHP v8.6.0
// session_encode: serializes $_SESSION with the internal session format (default handler "php":
// key names followed by serialize()-encoded values, joined with |). session_decode fills $_SESSION back.
// Never decode strings from untrusted sources - same injection surface as unserialize().
ini_set("session.save_path", sys_get_temp_dir());
session_start();
$_SESSION = [];
$_SESSION["user"] = "alice";
$_SESSION["visits"] = 3;
$_SESSION["tags"] = ["a", "b"];
$enc = session_encode();
session_write_close();
session_start();
$_SESSION = [];
$ok = session_decode($enc);
$rt = $_SESSION["user"] === "alice" && $_SESSION["visits"] === 3
&& $_SESSION["tags"] === ["a", "b"] && count($_SESSION) === 3;
session_write_close();
echo "encoded: ", $enc, "\n";
echo "decode returns: ", var_export($ok, true), "\n";
echo "user: ", $_SESSION["user"], "\n";
echo "visits: ", $_SESSION["visits"], "\n";
echo "round trip: ", var_export($rt, true);
encoded: user|s:5:"alice";visits|i:3;tags|a:2:{i:0;s:1:"a";i:1;s:1:"b";}
decode returns: true
user: alice
visits: 3
round trip: true
Python v3.15.2
import json
# Session payloads are serialized by the framework (Flask signs JSON with itsdangerous);
# json.dumps/loads is the language-level round trip counterpart
data = {"user": "alice", "visits": 3, "tags": ["a", "b"]}
encoded = json.dumps(data, separators=(",", ":"))
print("encoded:", encoded)
restored = json.loads(encoded)
print("user:", restored["user"])
print("visits:", restored["visits"])
print("round trip:", restored == data)
encoded: {"user":"alice","visits":3,"tags":["a","b"]}
user: alice
visits: 3
round trip: True
Rust v1.99.1
fn main() {
// serde_json's json! macro builds the payload; to_string/from_str is the round trip
// (Cargo.toml enables preserve_order to keep insertion order, matching PHP)
let data = serde_json::json!({"user": "alice", "visits": 3});
let encoded = data.to_string();
println!("encoded: {}", encoded);
let restored: serde_json::Value = serde_json::from_str(&encoded).unwrap();
println!("user: {}", restored["user"].as_str().unwrap());
println!("visits: {}", restored["visits"].as_i64().unwrap());
println!("round trip: {}", restored == data);
}
encoded: {"user":"alice","visits":3}
user: alice
visits: 3
round trip: true
TypeScript v26.13.1
// JSON.stringify/parse is the language-level round trip; framework session stores
// serialize with their own codecs (JSON, MessagePack, protobuf)
interface SessionData { user: string; visits: number; }
const data: SessionData = { user: "alice", visits: 3 };
const encoded: string = JSON.stringify(data);
console.log("encoded:", encoded);
const restored: SessionData = JSON.parse(encoded);
console.log("user:", restored.user);
console.log("visits:", restored.visits);
console.log("round trip:", JSON.stringify(restored) === encoded);
encoded: {"user":"alice","visits":3}
user: alice
visits: 3
round trip: true
Language differences
C: no built-in serialization — cJSON-style libraries do the JSON round trip; replicating PHP's session storage format would mean designing an encoding yourself (key-value splicing).
C++: nlohmann/json dump/parse round trip (mind that keys come out alphabetically, not in insertion order); Boost.Serialization covers binary serialization.
C#: framework session storage (ASP.NET Session, distributed caches) uses System.Text.Json or BinaryFormatter (deprecated and unsafe — the same lesson as unserialize); JsonSerializer.Serialize/Deserialize is the modern standard.
Go: encoding/json Marshal/Unmarshal round trip; struct field order is the output order (PHP uses $_SESSION insertion order).
Java: org.json keeps insertion order; real projects use Jackson (ObjectMapper.writeValueAsString/readValue). Java's native ObjectOutputStream serialization is likewise an untrusted-input injection surface (the classic deserialization vulnerability zone).
JavaScript: JSON.stringify/parse round trip; when express-session stores to Redis/Mongo the codec is store-driven (connect-redis uses JSON or msgpack).
PHP: with the default session.serialize_handler=php the format is key name | serialize(value) concatenated — the value part matches serialize() (see the serialize/unserialize entry), the key part does not; session_decode on untrusted input is the same object-injection surface as unserialize (if an attacker can write session data, e.g. pollute a shared store, decoding fires the gadget chain); also, from PHP 8.4 session.serialize_handler=php_serialize is available (one serialize string per session, so keys containing | survive).
Python: the framework layer is the real codec (Flask signs JSON with itsdangerous, Django uses PickleSerializer — pickle is equally a classic injection surface, JSON is safer across trust boundaries).
Rust: serde_json round trip (compile-time typing, no runtime injection surface); axum-session serializes session data with serde.
TypeScript: same as JavaScript.