Zend PHP 7 Certification – Web Features – Cookies

This post covers the Cookies section of the Web Features chapter when studying for the Zend PHP 7 Certification.

Cookies are a mechanism for storing data in the remote browser and tracking or identifying return users.

You can set cookies in PHP using the setcookie() or setrawcookie() function. Cookies are part of the HTTP header, so setcookie() must be called before any output is sent to the browser. This means that no output should be specified before.

Any cookies sent to you from the client will automatically be included into a $_COOKIE auto-global array.

Cookie data from the client is automatically sent to $_COOKIE if the parameters of variables_order() include C.

The setcookie() function sends a cookie where the value is url encoded. It takes a few parameters.

  • string $name – The name of the cookie.
  • string $value – The value of the cookie.
  • int $expire = 0 – The time the cookie expires. If set to 0, or omitted, the cookie will expire at the end of the session (when the browser closes).
  • string $path – The path on the server in which the cookie will be available on. If set to /, the cookie will be available within the entire domain. If set to /foo/, the cookie will only be available within the /foo/ directory and all sub-directories such as /foo/bar/ of the domain.
  • string $domain – The (sub)domain that the cookie is available to
  • $secure = false – Indicates that the cookie should only be transmitted over a secure HTTPS connection from the client. When set to TRUE, the cookie will only be set if a secure connection exists.
  • $httponly = false – When TRUE the cookie will be made accessible only through the HTTP protocol. This means that the cookie won’t be accessible by scripting languages, such as JavaScript.
setcookie("somecookie", "somevalue", "0", "/", "somesite.com", false, false);
echo $_COOKIE['somecookie']; // Outputs: somevalue

setcookie("somecookie", "Fish & Chips cost $5!", "0", "/", "somesite.com", false, false);
echo $_COOKIE['somecookie']; // Outputs: Fish+%26+Chips+cost+%245%21

The setrawcookie() function sends a cookie without urlencoding the cookie value. It takes the same parameters as setcookie().

When deleting a cookie you should assure that the expiration date is in the past, to trigger the removal mechanism in your browser.

setcookie("TestCookie", "", time() - 3600);

An easier way to do this would be to write the following.

setcookie("TestCookie", "", 1);

Where the TestCookie cookie is overridden by a blank cookie that expires 1 second after the epoch (1 January 1970 00:00:00 UTC).

Note: This article is based on PHP version 7.1.