Skip to content

Instantly share code, notes, and snippets.

@sokil
Created May 2, 2022 20:13
Show Gist options
  • Save sokil/9e179e582bdcdd392774cce3b31b2b17 to your computer and use it in GitHub Desktop.
Save sokil/9e179e582bdcdd392774cce3b31b2b17 to your computer and use it in GitHub Desktop.
php session serializer
<?php
function sessionDataUnserialize($serializedData) {
$return_data = array();
$offset = 0;
while ($offset < strlen($serializedData)) {
if (!strstr(substr($serializedData, $offset), "|")) {
throw new Exception("invalid data, remaining: " . substr($serializedData, $offset));
}
$pos = strpos($serializedData, "|", $offset);
$num = $pos - $offset;
$varname = substr($serializedData, $offset, $num);
$offset += $num + 1;
$data = unserialize(substr($serializedData, $offset));
$return_data[$varname] = $data;
$offset += strlen(serialize($data));
}
return $return_data;
}
function sessionDataSerialize(array $data) {
$result = [];
foreach ($data as $key => $value) {
$result[] = $key . '|' . serialize($value);
}
return implode('', $result);
}
$sessionData = 'intkey|i:42;stringkey|s:3:"str";arraykey|a:2:{s:3:"int";i:42;s:6:"string";s:3:"str";}stdclasskey|O:8:"stdClass":2:{s:3:"int";i:42;s:6:"string";s:3:"str";}';
var_dump($sessionData === sessionDataSerialize(sessionDataUnserialize($sessionData)));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment