Cookies in PHP

What are cookies?

We can say cookies to be a type of message sent to a browser by a web server.

Cookies help the developers to remember the user and provide them more efficient browsing data, such as the ad widgets on the bottom right section of displaying the ads related to what you have been googling everyday.

When I say this, I am also aware that cookies created by one website can be used by another website too.

How does a cookie work?

Based on the code that has been written and executes on the server, the response object returned from the server, contains a header for set-cookie, that commands the browser to set the applicable cookies in the browser.

Browser creates a sort of text file, puts in the information sent by the server and stores it in a browser directory in the hard disk.

The subsequent request made to the server now checks for the cookie specific to the server domain. If there is a match, the cookie is also sent to the server along with the request. Server keeps all the information available with the cookie in environment variables $_COOKIE or $HTTP_COOKIE_VARS[], which holds all the cookie names and their corresponding values.

How to set a cookie in PHP?

In the above code, we have set two cookies, which will expire in the next 60 minutes.

“/” denotes that the cookie is valid for all the directories on the domain.

“” means that the cookies are restricted to the host which created it and will not be available to any of its subdomains. If instead I would have provided the domain name here, such as “”, the cookie would then be available across the domain including the subdomains.

Accessing cookies

Deleting a cookie

To delete the cookie, the safest option is to set the same cookie with a past date or a date that has already expired, such as:

Receive our updates to your inbox

Get more stuff like this
in your inbox

Subscribe to our mailing list and get interesting stuff and updates to your email inbox.