I'm using PHP session handler to implement persistent session on my site. The problem is that at some point, I need to insert the user_key into another MySQL table and I don't know how to retrieve that information from the code.
For example, the data row into my session table is:
active|i:1487613760;user_username|s:20:"v.lima06@hotmail.com";user_key|s:8:"a5186adc";authenticated|b:1;user_name|s:12:"victor";user_email|s:20:"v.lima06@hotmail.com";remember|b:1;
and I would like to know if there is a simple way to get the user_key variable.
Sorry if it was a bit confusing.
First option is to unserialize this string. http://php.net/manual/en/function.unserialize.php
Second option, You can use preg_match function with the next pattern:
preg_match('/user_key\|s:\d+:"([a-zA-Z0-9]+)"/', $string, $match);
I cant find anywhere something to handle that format of serialized string, its not something I've seen before.
However, heres a quick function to turn it into an array (it might not be overly elegant, but I've only had 1 coffee):
$string = 'active|i:1487613760;user_username|s:20:"v.lima06@hotmail.com";user_key|s:8:"a5186adc";authenticated|b:1;user_name|s:12:"victor";user_email|s:20:"v.lima06@hotmail.com";remember|b:1;
';
$array = deserializeSessionString($string);
echo $array['user_key'];
// deserialize a session string into an array
function deserializeSessionString($string)
{
$output = [];
// separate the key-value pairs and iterate
foreach(explode(';', $string) as $p) {
// separate the identifier with the contents
$bits = explode('|', $p);
// conditionally store in the correct format.
if(isset($bits[1])) {
$test = explode(':', $bits[1]);
switch($test[0]) {
// int
case 'i':
$output[$bits[0]] = $test[1];
break;
case 's':
// string
// ignore test[1], we dont care about it
$output[$bits[0]] = $test[2];
break;
case 'b':
// boolean
$output[$bits[0]] = ($test[1] == 1 ? true : false);
break;
}
}
}
return $output;
}
then you should be able to access what you need with just the key:
echo $array['user_key'];
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.