Javascript/PHP Cookies, the PHP code

This is the code for the PHP portion of this article, to go back to the Javascript code go Here

PHP keywords, functions and properties used :

$_COOKIE[], $_SERVER[] function, return, if, elseif, Ternary operation:condition ? if true : if false, true/false, setcookie(), time(), preg_match(), count(),

The PHP script tag

The PHP script tag

<?php

Although a server can be configured to accept an opening PHP tag using only "<?", not only is that a bad idea as there are other scripting languages that use the same characters, one can not always assume that a given server is configured to support its use.

If the "php" is not included and the server is not configured correctly, the script itself will be served as whatever the default data type is, which in most cases is text/html, leading to security issues. For portability and security reasons, using the full tag, including the "php" is strongly advised in all cases.

PHP Function interface

The function interface

function processCookie($cookieName,$func,$name,$value="",$days=365)

The PHP function interface is virtually identical to the Javascript function interface except the inclusion of default values for the $value and $days parameters.

PHP "Kill" process...

The Kill process

if ($func == "kill" || ($cookieName == $name && $func == "clear")) {
  setcookie($cookieName
           , ""
           , time() - 3600);
           , "/"
           , ".".$_SERVER['SERVER_NAME']);
  return true;
}
  1. Check to see if the requested function is either kill or, if the cookieName and name parameters are the same and the request function is clear.
  2. Set a cookie of the same name, path and domain with an expire time in the past. This will replace any existing cookie of the same name and cause the browser to delete the cookie. Note, the cookie will not actually be removed from the browser until either the user navigates away from the site or closes their browser.
PHP Initialization...

Initialize parameters for remaining processes

$nameQuery = $cookieName == $name ? $name . "=" : $name . "-";
$thisCookie = $_COOKIE[$cookieName];
$cookieString = "";
  • $nameQuery is used for searching for the required named value. If the cookie is a stacked cookie, the name/value separator is a "-", if non-stacked, "=". This makes searching for the required string in different places easier.
  • $thisCookie is used to contain the targetted cookie, if it exists. Notice that in PHP, all cookies contained in a request are contained in a server global variable, similar to $_GET[], $_POST[], $_REQUEST[] etc. To access a given cookie, simply provide the name of the cookie in the array key. As the cookie name is contained in $cookieName, providing that as the $_COOKIE[] key returns the required cookie, if it exists, without having to iterate through the entire cookie string.
  • $cookieString is used to contain data that will eventually be written to a cookie.
PHP "Clear" and "Set" process...

The Clear and Set process

if ($func == "clear" || $func == "set") {
  if ($func == "clear") {
    . . .
  } elseif ($func == "set") {
    . . .
  }
  $expires = time()+60*60*24*$days;
  setcookie($cookieName
           ,$cookieString
           ,$expires
           ,"/"
           ,".".$_SERVER['SERVER_NAME']);
  return true;
}

This if/else structure is used to consolidate the expiry and document cookie setting process required by the clear and set processes.

The actual clear and set processing, shown following this, exist in place of the ellipses in the code shown above.

PHP "Clear" process...

The Clear process

$myregexp = "(\\|" . $nameQuery . "[\\w]*|"
            . $nameQuery . "[\\w]*\\||"
            . $nameQuery . "[\\w]*)";
$cookieString = preg_replace($myregexp,"",$thisCookie);
  1. Construct a regular expression with the possible separator options, |name-value, name-value| or just name-value depending on the name/value pair's position.
  2. Replace any results with an empty string.
PHP "Set" process...

The Set process

if ($cookieName == $name || $thisCookie == "")
  $cookieString = $nameQuery . $value;
else {
  $myregexp = "/" . $nameQuery . "([\\w]*)/";
  preg_match($myregexp, $thisCookie, $matches);
  if ($matches != null && count($matches) > 0 && $matches[1] != "")
    $cookieString = str_replace($matches[1], $value, $thisCookie);
  else
    $cookieString = $thisCookie 
                  . ($thisCookie != "" ? "|" : "") 
                  . $nameQuery . $value;
}
  1. Check to see if we are dealing with a stacked cookie or not and if stacked, whether or not there is any existing cookie data.
  2. If not stacked, or there is no existing stacked cookie data, skip down to the simpler process of simply adding the given name/value pair.
  3. If stacked and there is existing data, step through the name/value pairs searching for the required pair. If/when found, URLEncode the value and add it, otherwise, add, as is, any other name/value pairs contained in the same stacked cookie using the "|" name/value pairs separator.
PHP "Read" process...

The Read process

if ($func == "read") {
  if ($thisCookie != null && $thisCookie != "") {
    $myregexp = "/" . $nameQuery . "([\\w]*)/";
    preg_match($myregexp, $thisCookie, $matches);
    if ($matches != null && count($matches) > 0 && $matches[1] != "")
      return $matches[1];
  }
  return null;
}
  1. Check to see if there is any cookie data at all, if not, return null
  2. Construct a regular expression to use as a search.
  3. Execute the regex and return whatever matches
  4. If nothing matches, return null.
The whole shebang...

The whole shebang

Putting it all together. . .

<?php
function processCookie($cookieName,$func,$name,$value="",$days=365) {
  if ($func == "kill" || ($cookieName == $name && $func == "clear")) {
    setcookie($cookieName,"",time() - 3600);
    return true;
  }

  $nameQuery = $cookieNameName == $name ? $name . "=" 
                                        : $name . "-";
  $thisCookie = $_COOKIE[$cookieName];
  $cookieString = "";

  if ($func == "clear" || $func == "set") {
    if ($func == "clear") {
      $myregexp = "(\\|" . $nameQuery . "[\\w]*|"
                  . $nameQuery . "[\\w]*\\||"
                  . $nameQuery . "[\\w]*)";
      $cookieString = preg_replace($myregexp,"",$thisCookie);
    } elseif ($func == "set") {
      if ($cookieName == $name || $thisCookie == "")
        $cookieString = $nameQuery . $value;
      else {
        $myregexp = "/" . $nameQuery . "([\\w]*)/";
        preg_match($myregexp, $thisCookie, $matches);
        if ($matches != null && count($matches) > 0 && $matches[1] != "")
          $cookieString = str_replace($matches[1], $value, $thisCookie);
        else
          $cookieString = $thisCookie 
                        . ($thisCookie != "" ? "|" : "") 
                        . $nameQuery . $value;
      }
    }
    $expires = time()+60*60*24*$days;
    setcookie($cookieName
             ,$cookieString
             ,$expires
             ,"/"
             ,".".$_SERVER['SERVER_NAME']);
    return true;
  }
  
  if ($func == "read") {
    if ($thisCookie != null && $thisCookie != "") {
      $myregexp = "/" . $nameQuery . "([\\w]*)/";
      preg_match($myregexp, $thisCookie, $matches);
      if ($matches != null && count($matches) > 0 && $matches[1] != "")
        return $matches[1];
    }
    return null;
  }
}
?>

Go back to the Javascript portion of the code Here