Getting Rid of "Magic Quotes" in Cookies

Magic quotes which were covered and hated in the previous chapter, as well also apply to cookies because they are data coming from the client. So if magic_quotes is on, single and double quotes are escaped with backslash characters. To get rid of those, this code is used. A similar code was also used in the previous chapter to remove these escape characters from form data (GET and POST data).

If magic_quotes is set, stripslashes() is applied recursively to all data in $_COOKIE.

Removing "Magic Quotes" from Cookies

  function stripCookieSlashes($arr) {
    if (!is_array($arr)) {
      return stripslashes($arr);
    } else {
      return array_map('stripCookieSlashes', $arr);
  if (get_magic_quotes_gpc()) {
    $_COOKIE  = stripCookieSlashes($_COOKIE);

This file should then be included in all PHP scripts that read cookies, using this statement:

require_once ''

Setting a (Reasonable) Cookie Expiry Date

The expiry date of a cookie is the third parameter for setcookie(). It is an integer value; therefore, the epoche value for a time stamp must be used. Tutorial 3, "Date and Time," contains quite a lot of information on how to work with this type of information.

Setting a Cookie with a Relative Expiry Date

  setcookie('version', phpversion(), time() +
Tried to send cookie.

Usually, it is a good thing to set a relative expiry date for a cookie ("in three weeks") rather than an absolute date ("end of May 2006"). If you use absolute dates, you might have to change your script on a regular basis because the absolute expiry date might arrive soon. It is also considered very unprofessional to set expiry dates that are in the very distant future, for instance in the year 2030. The client that receives this cookie will most certainly not be booted any more in that year.

Therefore, use a relative date. The PHP function time() retrieves the current epoche value; then add to this the number of seconds you want the cookie to live. The code at the beginning of This sets a cookie that will exist for three weeks.

by BrainBellupdated