I am getting the error:
Cookie names cannot contain any of the following ‘=,; trn1314’;
However, I have php code to replaced these characters before calling setcookie:
$notallowed = array('"', '=', ',', ';', ' ', 't', 'r', 'n', '13', '14', ""); // clean cookie names of potential invalid characters $name = str_replace($notallowed, "_", $name); setcookie($name, $value, $expire, $path, $domain, $secure);
It seems that setcookie chokes on other characters as well.
When I test the contents of $name
using the code below, I get the following
for ( $pos=0; $pos < strlen($name); $pos ++ ) { $byte = substr($name, $pos); echo 'Byte ' . $pos . ' of $name has value ' . ord($byte) . "<br>"; }
Output:
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
Can you help me add to my code to filter out invalid characters in the name? Thanks.
Advertisement
Answer
Your special character escape values are not double-quoted so they are treated as literal strings, ie 't'
vs "t"
.
You might want to consider using a regex to replace as @mynd mentioned:
$name = "Hi this n is a cookie; name"; $name = preg_replace('/[^a-z0-9]/i', '_', $name); echo $name; //Hi_this___is_a_cookie__name