Reputation: 33
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 ;
}
Upvotes: 1
Views: 849
Reputation: 10847
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.
Upvotes: 0
Reputation: 4854
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];
Upvotes: 0
Reputation: 94157
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.
Upvotes: 8