Click to See Complete Forum and Search --> : [RESOLVED] Extracting values from long string
nicky77
09-02-2008, 07:49 AM
Hi guys, i think this should be pretty straightforward but I'm not too sure how to do it. I need to extract certain values from an encoded cookie, such as username and password etc. When i decode the cookie, i am left with a string such as the following:
s:5:"email";s:29:"email@yahoo.com";s:8:"username";s:8:"theuser1";s:8:"password";s:50:"c4b16518512c64eba2ca9752ce50f690f9e3d105cbadd47066";
If I want to extract the email, username and password values, what is the best way to split up the string?
Thanks in advance for any help!
Phill Pafford
09-02-2008, 09:41 AM
explode might be good for this
$str = 's:5:"email";s:29:"email@yahoo.com";s:8:"username";s:8:"theuser1";s:8:"password";s:50:"c4b16518512c64 eba2ca9752ce50f690f9e3d105cbadd47066';
$parts = explode('";s:8:"', $str);
foreach($parts as $k => $v)
{
echo "Key: " . $k . " Value: " . $v . "<br />";
}
you might have to refine it to get the values you want but it should work
legendx
09-02-2008, 09:51 AM
That 'encoded cookie' looks serialized to me.. but I'm not 100% positive.
Checkout unserialize() (http://php.net/unserialize)
nicky77
09-02-2008, 11:13 AM
Cheers for the replies. Legendx, you're right it looks like a serialized object - the only thing is that when i try to unserialize it i get a blank result. The actual decoded output is much longer than the one i originally posted, here it is:
session_id|s:32:"cfaeda9cfb76b9571c0ea70f0351b69a";total_hits|i:34;_kf_flash_|a:0:{}user_agent|s:90:"Mozilla/5.0 (Windows; U; Windows NT 6.0; en-GB; rv:1.9.0.1) Gecko/2008070208 Firefox/3.0.1";ip_address|s:12:"27.236.81.31";last_activity|i:1220370914;auth_user|O:10:"User_Model":6:{s:14:"�*�object_name";s:4:"user";s:9:"�*�object";a:6:{s:2:"id";i:12;s:5:"email";s:29:"email@yahoo.com";s:8:"username";s:8:"theuser1";s:8:"password";s:50:"c4b16518512c64 eba2ca9752ce50f690f9e3d105cbadd47066";s:6:"logins";i:23;s:10:"last_login";i:1220365480;}s:10:"�*�changed";a:0:{}s:9:"�*�loaded";b:1;s:8:"�*�saved";b:1;s:10:"�*�sorting";a:1:{s:2:"id";s:3:"asc";}}
nicky77
09-02-2008, 12:02 PM
Sorted - used session_decode() instead of unserialize()
This will work for your original string.
$string='s:5:"email";s:29:"email@yahoo.com";s:8:"username";s:8:"theuser1";s:8:"password";s:50:"c4b16518512c64 eba2ca9752ce50f690f9e3d105cbadd47066";';
$pattern='/"[a-z A_Z @ \. 0-9]*"/';
preg_match_all($pattern,$string,$parts);
//print_r($parts);
foreach($parts as $v0){
foreach($v0 as $k => $v){
if($k=='1') $email=$v;
if($k=='3') $username=$v;
if($k=='5') $password=$v;
}
}
echo $email.'<br>';
echo $username.'<br>';
echo $password.'<br>';
Will the cookie info vary? As long as it label/value you can combine the odd/even keys then examine the keys for the one you want.
$parts = explode('";s:8:"', $str);
The s:x value is not the same Phil so that wouldn't work.