cookie 名称中的无效字符超出了错误消息中列出的字符范围

Invalid character in cookie name beyond what is listed in the error message

我收到错误:

Cookie names cannot contain any of the following '=,; \t\r\n34';

但是,在调用 setcookie 之前,我有 php 代码来替换这些字符:

$notallowed = array('"', '=', ',', ';', ' ', '\t', '\r', '\n', '3', '4', "[=10=]");
// clean cookie names of potential invalid characters
$name = str_replace($notallowed, "_", $name);    

setcookie($name, $value, $expire, $path, $domain, $secure);

似乎 setcookie 对其他角色也有影响。


当我使用下面的代码测试 $name 的内容时,我得到以下内容

for ( $pos=0; $pos < strlen($name); $pos ++ ) {
 $byte = substr($name, $pos);
 echo 'Byte ' . $pos . ' of $name has value ' . ord($byte) . "<br>";
}

输出:

Byte 0 of $name has value 115 
Byte 1 of $name has value 45 
Byte 2 of $name has value 103 
Byte 3 of $name has value 50 
Byte 4 of $name has value 49 
Byte 5 of $name has value 56 
Byte 6 of $name has value 49 
Byte 7 of $name has value 13 
Byte 8 of $name has value 181 
Byte 9 of $name has value 219 
Byte 10 of $name has value 93 
Byte 11 of $name has value 118 
Byte 12 of $name has value 215 
Byte 13 of $name has value 93 
Byte 14 of $name has value 181 
Byte 15 of $name has value 219 
Byte 16 of $name has value 93 
Byte 17 of $name has value 181 

你能帮我添加到我的代码中以过滤掉名称中的无效字符吗?谢谢。

您的特殊字符转义值未被双引号括起来,因此它们被视为文字字符串,即 '\t'"\t".

您可能需要考虑使用正则表达式来替换 @mynd 提到的:

$name = "Hi this \n is a cookie; name";

$name = preg_replace('/[^a-z0-9]/i', '_', $name);

echo $name; //Hi_this___is_a_cookie__name