简体   繁体   English

Cookie值是数组是否合法?

[英]Is it legal for a cookie value to be an array?

I always assumed that cookies may only hold strings, but the way PHP handles cookies, it is also possible to store an array in a cookie (and I'm not talking about serialized array, but a native array). 我一直认为cookie可能只包含字符串,但是PHP处理cookie的方式也可以将数组存储在cookie中(我不是在谈论序列化数组,而是本地数组)。 All you need to do is this: 您需要做的就是:

setcookie('a[1]', 'a');
setcookie('a[2]', 'b');
var_dump($_COOKIE);

The above will produce the following (remember to execute it twice): 上面将产生以下结果(记住要执行两次):

array(1) {
  ["a"]=>
  array(2) {
    [1]=>
    string(1) "a"
    [2]=>
    string(1) "b"
  }
}

What's going on here? 这里发生了什么? Clearly we managed to store an array to a cookie, which is supposed to hold strings only. 显然,我们设法将数组存储到cookie中,该cookie应该仅包含字符串。 Is this a bug? 这是错误吗?

It is certainly not a bug. 这当然不是错误。 As a matter of fact it is documented in PHP Documentation 事实上,它已记录在PHP文档中

You may also set array cookies by using array notation in the cookie name. 您还可以通过在cookie名称中使用数组符号来设置数组cookie。 This has the effect of setting as many cookies as you have array elements, but when the cookie is received by your script, the values are all placed in an array with the cookie's name: 这样可以设置与数组元素一样多的cookie,但是当脚本接收到cookie时,所有值都将以cookie的名称放置在数组中:

A cookie value can only be a string. Cookie值只能是字符串。

When PHP parses the cookies into $_COOKIE , certain naming conventions (ie cookies with names that end in [] or [something] ) will cause it to represent them as an array. 当PHP将cookie解析为$_COOKIE ,某些命名约定(即,名称以[][something]结尾的cookie)将导致其将它们表示为数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM