Using Cookies in PHP
In this tutorial you'll learn about using Cookies in PHP - what is a Cookie?, why do we need cookies?, how to set, reset and destroy cookies using PHP.
What is a Cookie?
Cookies are small bits of information that can be stored on a client computer. Once a cookie is created, it will expire after a specified time period. All the information stored in a cookie exist until it expires or deleted by the user.
Why do we need Cookies?
Now-a-days most of the websites use cookies to store small amounts of information. Websites can read the values from the cookies and use the information as desired. The browser is capable of keeping track of the websites and their corresponding cookies and is capable of reading the information from relevant cookies. Some common use of cookies include:
- User's aesthetic preference for a specific site.
- User keys to link them with their personal data - as used by many Shopping Cart Applications.
- Allowing a user to remain 'logged on' until he explicitly logs out or the browser window is closed.
How to create a cookie
Cookies can be set using the 'setcookie' function in PHP. This function takes three arguments - name of the variable, value of the variable and the expiry time period. The syntax to set a cookie using PHP is as given below:
setcookie("variable","value","time");
- variable - name of the cookie variable
- variable - value of the cookie variable
- time - expiry time
Example: setcookie("Test",$i,time()+3600);
- Test - cookie variable name
- $i - value of the variable 'Test'
- time()+3600 - denotes that the cookie will expire after an one hour
How to reset/destroy a cookie
There are several ways to destroy cookies. Cookies can be deleted either by the client or by the server. Clients can easily delete the cookies by locating the Cookies folder on their system and deleting them. The Server can delete the cookies in two ways:
- Reset a cookie by specifying expiry time
- Reset a cookie by specifying its name only
Reset a cookie using name:
Syntax:
setcookie('cookiename');
Example:
setcookie("test");
Reset/Destroy a cookie using expiry time:
The cookie can be set with an expiry time while creating the cookie using the 'setcookie' function. This is also a method used to destroy cookies.
Syntax:
setcookie("variable","value","time");
- variable - name of the cookie variable
- variable - value of the cookie variable
- time - expiry time