PHP Cookies are small pieces of data that can be stored on the computer of the user in order to track his or her browsing behavior.
Cookie files are used in order to store information about users, such as the user’s login credentials or the contents of their shopping carts.
Besides tracking user behavior, they can also be used to gather information about the pages and products that a user is visiting on the site.
The purpose of this article is to describe some of the basic methods for setting and managing cookies in PHP, such as defining and retrieving cookie values, deleting cookies, and handling cookie security issues, and to go over just some of these methods.
What is a Cookie?
A cookie is a piece of information that is used to identify a particular user. Basically, cookies are just small files that a server embeds on the back of a user’s computer when they visit it.
The cookie will be sent every time a computer requests a page through a browser, and it will be sent each time a page is requested.
Using PHP, you can both create cookies as well as retrieve the values stored in them.
PHP Cookies Creation
Using the setcookie() function, you can create a cookie that will be stored on your computer.
setcookie(name, value, expire, path, domain, secure, httponly);
There is only one parameter required, which is the name parameter and rest of the parameters are optional.
below example checks if a cookie named $c_name is set. If it is set, it displays its value to the user, and if it is not set, it informs the user that the cookie is not set.
Php Cookie Example: 1
Php Cookie Example: 2
When the cookie is sent, it will be automatically encoded with URL encoding, and when it is received, it will automatically decode it with the same encoding (to prevent URLencoding, make sure you use setrawcookie() instead).
PHP Cookie Value Modification
The following are the steps that you can follow if you wish to modify a cookie value in PHP:
- Using the $_COOKIE superglobal array, you can retrieve the value of an existing cookie.
- As needed, make adjustments to the value.
- The setcookie() function must be used again with the modified value in order to set the cookie again.
Here, we are using above example 1 to modify data in cookie:
Using the setcookie() function in PHP you can delete a cookie by setting its expiration time to a past time, following which the cookie will be deleted.
Here is an example of how to delete a cookie:
Php Cookie Delete Example: 1
Here is another example of deleting cookies from the above example 2: