Created
September 7, 2011 19:04
-
-
Save phred/1201412 to your computer and use it in GitHub Desktop.
Simple reliable and non-regex method to unserialize PHP session data
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// This is the result of about an hour's delving into PHP's hairy-ass serialization internals. | |
// PHP provides a session_decode function, however, it's only useful for setting the contents of | |
// $_SESSION. Say, for instance, you want to decode the session strings that PHP stores in its | |
// session files -- session_decode gets you nowhere. | |
// | |
// There are a bunch of nasty little solutions on the manual page[1] that use pretty hairy regular | |
// expressions to get the job done, but I found a simple way to use PHP's unserialize and recurse | |
// through the string extracting all of the serialized bits along the way. | |
// | |
// It's not speedy (it calls unserialize AND serialize for each session element), but it's accurate | |
// because it uses PHP's internal serialized object parser. Fun trivia: PHP's serialized object | |
// parser is an ugly-ass little compiled regular expression engine. But hey, it works, let's not | |
// reinvent this wheel. | |
// | |
// [1]: http://www.php.net/manual/en/function.session-decode.php | |
// | |
define("SESSION_DELIM", "|"); | |
function unserialize_session($session_data, $start_index=0, &$dict=null) { | |
isset($dict) or $dict = array(); | |
$name_end = strpos($session_data, SESSION_DELIM, $start_index); | |
if ($name_end !== FALSE) { | |
$name = substr($session_data, $start_index, $name_end - $start_index); | |
$rest = substr($session_data, $name_end + 1); | |
$value = unserialize($rest); // PHP will unserialize up to "|" delimiter. | |
$dict[$name] = $value; | |
return unserialize_session($session_data, $name_end + 1 + strlen(serialize($value)), $dict); | |
} | |
return $dict; | |
} | |
$session_data = …; // A string from a PHP session store. | |
$session_dict = unserialize_session($session_data); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment