tags:

views:

49

answers:

4

I have a session variable that contains the following string.

a:2:{s:7:"LoginId";s:32:"361aaeebef992bd8b57cbf390dcb3e8d";s:8:"Username";s:6:"aaaaaa";}

I want to extract the value of username "aaaaaa". can anyone suggest easier/more efficient manner?

$session_data = unserialize($_SESSION["SecurityAccess_CustomerAccess"]);
$session_user_array = explode(';', $_SESSION["SecurityAccess_CustomerAccess"]);
$temp = $session_user_array[3]; 
$temp = explode(':', $temp);
$username = $temp[2];
echo $username; 
+7  A: 

This is all you need:

$session_data = unserialize($_SESSION["SecurityAccess_CustomerAccess"]);
echo $session_data['Username'];

Your session data is an array stored in serialized form, so unserializing it turns it back into a regular PHP array.

zombat
big ralph
A: 

If the data will always be formed in a similar manner, I would suggest using a regular expression.

preg_match('/"Username";s:\d+:"(\w*)"/',$session_data,$matches);
echo $matches[1];
Josiah
However if the arguments aren't always in that order you will need /"Username";s:\d+:"(.*?)"/
SimpleCoder
Is a working but wrong solution. Unserialization is the right way.
Mikulas Dite
A: 

It just got uglier... had to removed quotes.

if ($_SESSION["SecurityAccess_CustomerAccess"]){    
    $session_data = unserialize($_SESSION["SecurityAccess_CustomerAccess"]);
    $session_user_array = explode(';', $_SESSION["SecurityAccess_CustomerAccess"]);
    $temp = $session_user_array[3]; 
    $temp = explode(':', $temp);
    $temp = str_replace("\"", "", $temp[2]);
    $username = $temp;
      echo  $username ; 
}
big ralph
A: 

You could probably write a some type of regular expression to help with some of this if the placement of these values were always the same. But I think what you have here is great for readability. If anyone came after you they would have a good idea of what you are trying to achieve. A regular expression for a string like this would probably not have the same effect.

spinon