Escaping Special Characters and Quotes in Cookies

What is the difference between setcookie() and setrawcookie() function?

By default setcookie() function takes care of escaping special characters in the cookie values in URL format (similar output as of rawurlencode() function). Spaces convert to + and everything converts to a percent sign followed by its ASCII value in hexadecimal except periods, hyphens, underscores, letters, and digits. For example, a double quote " converts to %22 and @ converts to %40.

If you don’t want PHP to make changes to your cookie value, use setrawcookie() instead of setcookie(). The function setrawcookie() accepts the same parameter as setcookie(), but does not URL-encode the cookie’s value. You must do that manually, with the function urlencode() (or rawurlencode()).

 $value = 'Hi!';

 //URL-encode the value 
 setcookie('key', $value); // Hi%21

 //Does not esape the value
 setrawcookie('key', $value); // Hi!

Cookies and Sessions: