1

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; 

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 ; 
}

3 Answers 3

8

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.

Sign up to request clarification or add additional context in comments.

1 Comment

fuc&ing brilliant! got to read those 800 pages on strings and arrays!
0

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];

2 Comments

However if the arguments aren't always in that order you will need /"Username";s:\d+:"(.*?)"/
Is a working but wrong solution. Unserialization is the right way.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.