A cookie, which is also called as a browser cookie, is a small piece of data that can be stored in the local computer for future use. It accelerates the page loading speed and improves the reading experience to a large extent. There are two common uses of cookies listed in the following:
- It can store your username and password on the computer, so you don’t need to go through the logging process every time you visit a website.
- It can store the data for some movies, music, textual files, and many more, so you don’t need to wait for the downloading when you access them the next time.
Here, we have come out a beginners’ guide telling you how to set, retrieve, and delete cookies with the help of PHP coding.
PHP has the setcookie() function that can send an HTTP cookie to the local browser. The basic syntax of this function is setcookie(name, value, expire, path, domain, secure). Note that the name and value are URL encoded, and expire field determines when the browser can forget the cookie. Check an example in below.
In fact, not all the six arguments are required, among which the name and value are the must-have, and the rest are optional.
Set Cookies with PHP
You can set cookies with the setcookie() function of PHP. There is a special note that the code must be located before the html tag.
In this example, we have created a cookie with the name of user and the content of Alex. The code can only be retained for 3600 second that is one hour.
Retrieve Cookies with PHP
To access your cookies, you can make use of either $_COOKIE or $HTTP_COOKIE_VARS that are two of the powerful PHP variables. Check the example in the following.
Check Cookies are Set or Not
This requires you to use the isset() function to figure out whether a cookie has been set successfully or not.
Delete Cookies Using PHP
In order to delete a cookie, you have to call the setcookie() function with the augment of name. Besides, you’d better make sure that the expiration date is already in the past.