[英]How to get certain value from cookie string with PHP or JS?
A plugin I use stores multiple values in one string. 我使用的一个插件将多个值存储在一个字符串中。
var_dump looks like this: var_dump看起来像这样:
{\"strict\":\"0\",\"thirdparty\":\"1\",\"advanced\":\"0\"}
I need to check if, for example, "advanced" is true or not. 我需要检查例如“ advanced”是否正确。
Doing it in php would be great, JS would also be good. 用php来做会很棒,而JS也会很好。
$jsIn = '{\"strict\":\"0\",\"thirdparty\":\"1\",\"advanced\":\"0\"} ';
$jsOut = json_decode(stripslashes($jsIn));
<?php
$input = '{\"strict\":\"0\",\"thirdparty\":\"1\",\"advanced\":\"0\"}';
$input = str_replace('\', '', $input);
$input = json_decode($input, true);
$advanced = empty($input['advanced']);
If your string contains antislashes, you must remove it. 如果您的字符串包含反斜杠,则必须将其删除。 Here with PHP#str_replace
after that you decode the json string to have an association array and finally test $input['advanced']
with PHP#empty
that returns false
for false, 0, null, or '0' value otherwise true. 在此之后,使用PHP#str_replace
解码json字符串以具有关联数组,并最终使用PHP#empty
测试$input['advanced']
,该返回值将false
为false,0,null或'0',否则返回true。
Problem solved and works as intended. 问题已解决并且可以按预期工作。 So, first we get rid of the backslashes in the string that's the value of this cookie with stripslashes() , in wordpress use wp_unslash() . 因此,首先我们使用stripslashes()除去字符串中该cookie的值中的反斜杠,在wordpress中使用wp_unslash() 。 After json_decode() we have access to (in this case) three items ( strict, thirdparty, advanced ) which can have a value of 0 or 1 . 在json_decode()之后,我们可以访问(在这种情况下)三个项目( strict,thirdparty,advanced ),其值可以为0或1 。 Now, in the var_dump() each item contains string(1) before the actual value. 现在,在var_dump()中,每个项目在实际值之前都包含string(1) 。
string(1) "1"
string(1) "0"
The IF statement nevertheless works as intended. IF语句仍然按预期工作。
$input = json_decode( stripslashes( $_COOKIE['some-cookie'] ), true );
$thirdparty = $input['thirdparty'];
$advanced = $input ['advanced'];
var_dump( $thirdparty );
echo "<br>";
var_dump( $advanced );
echo "<br>";
if ($thirdparty > 0) {
echo "allowed";
} else {
echo "not allowed";
}
echo "<br>";
if ($advanced > 0) {
echo "allowed";
} else {
echo "not allowed";
}
Many thanks to all ... 非常感谢大家...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.