What's WP
Find Everything Related to WordPress - Best Tutoriasl on WordPress!
How to Set Cookie using PHP Coding - Effective Method for Better Reading

How to Set Cookie using PHP Coding – Effective Method for Better Reading

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:

  1. 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.
  2. 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.

Setcookie() Function

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.

cookie example

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.

code location

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.

Retrieve Cookies

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.

Check Cookies

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.

Delete Cookies


Susan Rose is a freelance writer who has a deep knowledge about WordPress. She loves everything related to website building since the freshman year at Christopher Newport University, and loves to share her experience with people all over all the world. In the daily life, Susan loves detective novels as it can train her logical thinking and creativity.