0

I am getting the error:

Cookie names cannot contain any of the following '=,; \t\r\n\013\014';

However, I have php code to replaced these characters before calling setcookie:

$notallowed = array('"', '=', ',', ';', ' ', '\t', '\r', '\n', '\013', '\014', "\0");
// 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.

mseifert
  • 5,390
  • 9
  • 38
  • 100
  • This might be helpful https://stackoverflow.com/questions/1969232/what-are-allowed-characters-in-cookies. Besides the solutions suggested in the mentioned thread it might also be worth considering to use a character whitelist instead of a blacklist. You could use a regex to find only guaranteed safe character like [a-z][A-Z][0-9] – mynd Apr 12 '21 at 17:56

1 Answers1

0

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
cOle2
  • 4,725
  • 1
  • 24
  • 26