In web programming, the term 'cookie' means something totally different from what it is popularly known as. In web programming, a 'cookie' is a small text file stored on a users hard drive by a website for various purposes such as remembering a user who frequents that website.
This tutorial focuses on:
- Setting a cookie
- Reading data from a cookie
Setting a cookie
The function used to set a cookie is setcookie(). A cookie must be sent along with the HTTP headers before any other code. This means that when using the setcookie() function it must be declared first thing on the page - even before the <HTML> tag used in the HTML code. If setcookie() is not the first thing on the page, then the function will fail, a cookie will not be set, and the function will return false! When a cookie is successfully sent, the function returns true.
The setcookie() function can take seven parameters, but only one is required - the name parameter (to set the name of the cookie).
setcookie() function parameters:
- name - Sets the name of the cookie.
- value - Sets the value of the cookie.
- expirationDate - Sets the expiration date of the cookie. If this parameter is not used, the cookie will expire when the browser is closed by default.
- path - Denotes to which directories on the server the cookie will be available. For example, if this parameter is set to '/dir5' then it will be available only to that directory and all its subdirectories. If this parameter is set to '/' (root directory) then it will be available to all directories on the server.
- domain - Denotes the domain in which the cookie will be available.
- isSecure - Takes a value of either true or false and denotes whether the cookie should be transmitted over a secure HTTPS connection or not.
The above example will set a cookie named cookie1 that stores the value 'this is a cookie'. This cookie will expire automatically when the web browser is closed since no expiration date is set for it.
Reading data from a cookie
To read data from a cookie, you first have to check if the cookie actually exists. This is achieved through the isset() function. The isset() function is used to check for the existence of a variable, in this case, a cookie variable through the use of the $_COOKIE associative array which stores an array of existing cookies.
If the cookie specified in the isset() function exists, then the function will return true, otherwise it will return false.
In the above example, an if statement checks for the existence of a cookie named cookie1. If it exists, then its value will be passed to the variable $cookie1. If it does not, then it will remain empty. The isset() function checks for this.