A COOKIE is a piece of data that the browser saves on the user's machine, usually in a temporary folder. Cookies can be useful as they store persistent data you can access from different pages of your Website, but at the same data they are not as secure as data saved in a server (like SESSION does).
You can create a cookie using setcookie() with this syntax:
setcookie(name, value, expire, path, domain, secure, httponly)
- name: is the name of the cookie e.g. username
- value: is the value (alfanumeric) of the cookie e.g. time() + (60*60*24*2) //2 days from now
- expire: timestamp of expiration date e.g. username
- path: path of the cookie on the server e.g. “/” (root: the cookie is accessible over the entire domain)
- domain: internet domain of the site e.g. www.mysite.com (for domain and subdomains)
- secure: boolean for secure or regular connection e.g.true/false
- httponly: boolean for http protocol e.g.true/false
For setcookie() only name and value are mandatory. Expire, path, domain, secure, httponly are optional.
You can use the $_COOKIE superglobal to access your cookies.
Setting a cookie:
//setting a cookie called username, with value of johnDoe that will last for 2 weeks
setcookie('username', 'johnDoe', time() +(60*60*24*14) );
Accessing a cookie:
//storing the value of the username cookie into a variable
if( isset($_COOKIE['username']) )
$username = $_COOKIE['username'];
Deleting a cookie:
To delete a cookie, you must set it again with same exact parameters, but with
EXPIRE set to a date in the past (e.g. previous month)
setcookie('username', 'johnDoe', time() - (60*60*24*30) ); //notice the minus here