PHP – Cookies
Cookies are files that are used for tracking and are stored on the client’s computer. PHP supports cookies that keep tracks of their returning users. The server sends the cookies that may contain information to the browser. All the sent information is then stored at the local system by the browser. If the user comes back with another request then these cookies information are sent to the server that identifies the user on the basis of the information.
These cookies information is sent in the HTTP header whose value will be URL encoded. This information will not be permanently stored on the system and can get expired. The expire field suggests the time by when the cookies will no longer be available to the server. If you connect to the server after the expiration of the cookie then the cookies are sent again to the server.
Syntax of Cookies within HTTP header
HTTP/1.1 200 OK Date: //date Server: //server detail Set-Cookie: name=xyz; expires=Friday, 04-Feb-20 22:03:38 GMT; path=/; domain=xxx.com Connection: close Content-Type: text/html
How to set a cookie with PHP
setcookie() function is supported by PHP that is defined with six arguments. This function is to call before the HTML tag.
setcookie(name, value, expire, path, domain, security);
- The name argument is the name of the cookies which can be accessed using the environment variable called HTTP_COOKIE_VARS.
- The value argument is used to set the value for the name variable.
- Expiry suggests the time of the cookie expiration, if no time is set then the browser will automatically erase the cookies once we close the browser.
- The path specifies the location which supports the cookie.
- A domain defines the location within the large domain for which the cookies are valid.
- Security, if this condition is set to 1 then the transmission is done via secure HTTP connection else the data is sent by regular HTTP.
<?php setcookie("name", "Jacob", time()+1800, "/","", 0); setcookie("age", "21", time()+1800, "/", "", 0); ?> <html> //body </html>
How to access a cookie with PHP
You can use PHP supported environment variables $_COOKIE and $HTTP_COOKIE_VARS to access the cookies.
<html> <head> <title>Accessing Cookies</title> </head> <body> <?php echo $_COOKIE["name"]. "<br />"; //or echo $HTTP_COOKIE_VARS["name"]. "<br />"; echo $_COOKIE["age"] . "<br />"; //or echo $HTTP_COOKIE_VARS["age"] . "<br />"; ?> </body> </html>
How to delete a cookie with PHP
Before deleting the cookie you can check if the cookie is set or not using isset() function by passing the cookie name as the argument. If the cookie is set then you can delete it using setcookie() function by passing only the name argument out of the six arguments.
<?php setcookie( "name", "", time()- 20, "/","", 0); setcookie( "age", "", time()- 20, "/","", 0); ?> <html> <head> <title>Deleting Cookies</title> </head> </html>