Set cookie and retrieve it on web page in PHP

By Faruque Ahamed Mollick

A cookie in PHP used to store the small amount of data on client side. The cookie actually a small text file that stores small data, nearly about 4KB. Cookies are generally used to keep tracking of information such as a username that the site can retrieve to personalize the page when user visit the website next time.

When a browser requests a web page to the server, the server automatically gets all the cookie data within the request.

How to set a cookie?

The setcookie() function in PHP is used to defines or set a cookie to be sent along with the rest of the HTTP headers. often a cookie used to identify a user.

After the cookie is set, the server embeds a small file on user’s computer that can be used by the server later. When the same computer requests a page from that server, it will also send the cookie to the server.

Below is the basic syntax to set a cookie:

setcookie(name, value, expire, path, domain, secure);

Each of the parameters for setcookie() function are given below:

  • name: This is the name of the cookie that will be used to retrieve the cookie.
  • value: This is the value of the cookie that can be used for a specific task.
  • expires : Expiry date or time for the cookie in UNIX timestamp format. This is the optional parameter. the cookie will expire after the specific time you set. In default, it will be 0. If this parameter not set or it is set to 0, the cookie will expire when the browser is closed.
  • path: This is an optional parameter for setcookie() function. This parameter specifies the path on the server for which the cookie will be available. If set to “/” the cookie will be available within the entire domain. The default value set to the current directory where the cookie is being set in.
  • domain: This is also an optional parameter which specifies the domain for which the cookie will be available.
  • secure: This is an optional parameter which specifies whether or not the cookie should only be transmitted over a secure HTTPS connection. The default value is FALSE. If it set to TRUE, then it indicates that the cookie will only be set if a secure connection exists.

Below is the example of setting the cookie:

   setcookie("name", "John Watson", time()+3600, "/","", 0);

Using the above code a cookie will be set which will be expired in one hour. now to retrieve the cookie, use the code that is given below:

 echo $_COOKIE["name"];

PHP provides another way of retrieving cookie:

echo $HTTP_COOKIE_VARS["name"];

To check if the cookie exists or not, you can use the PHP isset() function:

         if( isset($_COOKIE["name"]))
             echo "Hello " . $_COOKIE["name"] ;
              echo "Sorry... User not found";

I hope it will be helpful to you.


Leave a Reply

Your email address will not be published. Required fields are marked *