note 97509 added to function.session-decode

From: Date: Fri, 23 Apr 2010 12:01:20 +0000
Subject: note 97509 added to function.session-decode
Groups: php.notes 
Request: Send a blank email to php-notes+get-168543@lists.php.net to get a copy of this message
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!) ---- Server IP: 92.48.74.199 Probable Submitter: 81.134.131.2 ---- Manual Page -- http://www.php.net/manual/en/function.session-decode.php Edit -- https://master.php.net/note/edit/97509 Del: integrated -- https://master.php.net/note/delete/97509/integrated Del: useless -- https://master.php.net/note/delete/97509/useless Del: bad code -- https://master.php.net/note/delete/97509/bad+code Del: spam -- https://master.php.net/note/delete/97509/spam Del: non-english -- https://master.php.net/note/delete/97509/non-english Del: in docs -- https://master.php.net/note/delete/97509/in+docs Del: other reasons-- https://master.php.net/note/delete/97509 Reject -- https://master.php.net/note/reject/97509 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#168543) next »