Cookies are plain text files stored on the client side. You can use them for tracking purpose.
There are three steps to identify a returning user −
- Server sends a set of cookies to the client (browser). For example, id or token.
- Browser stores it.
- Next time a browser sends a request to the web server, it also sends those cookies, so that the server can use that information to identify the user.
Cookies are usually set in an HTTP header as shown in the following code.
HTTP/1.1 200 OK Date: Fri, 05 Feb 2015 21:03:38 GMT Server: Apache/1.3.9 (UNIX) PHP/4.0b3 Set-Cookie: name = myname; expires = Monday, 06-Feb-16 22:03:38 GMT; path = /; domain = tutorialspoint.com Connection: close Content-Type: text/html
PHP provides the setcookie() function to set cookies −
setcookie(name, value, expire, path, domain, security);
where −
- name − Sets the name of the cookie and is stored in an environment variable called HTTP_COOKIE_VARS.
- value − Sets the value of the named variable.
- expiry − Specifies a future time in seconds since 00:00:00 GMT on 1st Jan 1970. After this time cookie will become inaccessible.
- path − Specifies the directories for which the cookie is valid.
- domain − This can be used to define the domain name in very large domains. All cookies are only valid for the host and domain which created them.
- security − If set to, it means that the cookie should only be sent by HTTPS, otherwise, when set to 0, cookie can be sent by regular HTTP.
To access cookies in PHP, you may use the $_COOKIE or $HTTP_COOKIE_VARS variables.
<?php echo $_COOKIE["token"]. "<br />"; /* is equivalent to */ echo $HTTP_COOKIE_VARS["token"]. "<br />"; echo $_COOKIE["id"] . "<br />"; /* is equivalent to */ echo $HTTP_COOKIE_VARS["id"] . "<br />"; ?>
To delete a cookie, you should set the cookie with a date that has already expired.
<?php setcookie( "token", "", time()- 60, "/","", 0); setcookie( "id", "", time()- 60, "/","", 0); ?>