How to set cookies using PHP and get them via JavaScript

I had an application where I wanted to set a cookie value using the php setcookie function and then later pull out the value using JS. The problem is the php setcookie function url encodes the cookie values with ‘+’ symbols for any whitespace. When you later pull out the cookie value using the JS decodeURIComponent function the ‘+’ symbols remain, converting a string to like ‘abc cdf’ to ‘abc+cdf’. If you want to the cookie values to have ” ” rather than “+” then you need to str_replace all the “+” with “%20” after calling the php urlencode function and then save the encode string using setrawcookie. The basic call to do something this is:

setrawcookie("cookie", str_replace('+','%20',urlencode($string)), time() + 3600*24*7, "/path","");

Hopefully this will save someone some time. If you want to do the reverse it is very simple – just calling the php urldecode function on the server $_COOKIE variable.

$string = urldecode($_COOKIE['string']);

Of course all the usual warnings about not trusting user supplied data remain. Just because your script created the data does not mean you can trust what is actually there.

Leave a Reply

Your email address will not be published. Required fields are marked *