note 97509 deleted from function.session-decode by danbrown
| From: | danbrown@php.net | Date: | Fri, 23 Apr 2010 12:32:01 +0000 |
| Subject: | note 97509 deleted from function.session-decode by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-168544@lists.php.net to get a copy of this message | ||
Note Submitter: edam
----
In response to deminy, ac and bmorel's posts about creating a function to decode serialised
session data, the following works quite well (and handles '|' characters in the data):
<?
function unserialize_session_data( $data )
{
$result = array();
while( ( $pos = strpos( $data, '|' ) ) !== false ) {
$val = unserialize( substr( $data, $pos + 1 ) );
$result[ substr( $data, 0, $pos ) ] = $val;
$data = substr( $data, $pos + 1 + strlen( serialize( $val ) ) );
}
return $result;
}
?>
It's only weakness is that it relies on the length of serialised data that is unserialize()ed
and then serialize()ed again being the same. I'm sure you could craft valid serialised data
that this is not the case for, but where the serialised data came from session_encode() (or was
passed to a the session save handler's write() function), this assumption will always be ok, I
believe.
Also, for completeness, this will encode an arbitrary array in to a serialised session data string:
<?
function serialize_session_data( $data )
{
$result = '';
foreach( $data as $key => $val )
if( strpos( $key, '|' ) === false )
$result .= $key.'|'.serialize( $val );
return $result;
}
?>
(Note that keys in the $_SESSION array can't have a '|' character in them either!)