检索Cookie值的一部分并存储在变量中
我有一个ASP.NET登录应用程序。 登录成功后,我的应用程序会创建一个Cookie。检索Cookie值的一部分并存储在变量中
在创建时,我的饼干类似于这样的:
Name: LoginCookie
Value: guid=3eb8d82d-bc83-4ab9-b12b-880f84404a1d&login=true
我的问题是,用PHP,我怎么找回“的GUID”值,并将其存储在一个变量?
非常感谢任何指针。
parse_str($_COOKIE['LoginCookie'], $cookie);
// now 'guid' and 'login' are available in the array $cookie:
echo var_export($cookie, 1), PHP_EOL;
echo $cookie['guid'];
这很好。非常感谢您的帮助 :-) – michaelmcgurk 2012-03-29 06:57:51
你可以这样用正则表达式给出一个镜头:
$cookieValue = $_COOKIE['LoginCookie'];
preg_match('#guid=([\-a-f0-9]+)#', $cookieValue, $matches);
$guid = $matches[0];
如果GUID的格式总是这样,正则表达式可以被更新,以更具体。现在它会在guid = up之后匹配任何东西,直到它与非数字,小写字母(a-f)或短划线相匹配。
如果cookie位于key1 = value1 & key2 = value2 ...格式中,那么使用PHP的parse_str也是一个很好的选择。它采用URL参数样式字符串并将其分解为多个键/值对。
$cookieValue = $_COOKIE['LoginValue'];
parse_str($cookieValue, $cookieParts);
$guid = $cookieParts['guid'];
这种方式可能是一种更清晰的方法,可以将这些值从“PHP”中取出。
谢谢!看起来像parse_str是最好的前进方向。 – michaelmcgurk 2012-03-29 06:58:21
你为什么不设置两个单独的cookie? – ThiefMaster 2012-03-29 06:38:11