How to PHP Scripting- PHP Cookies

PHP cookies are a mechanism for storing data in the remote browser and thus tracking or identifying return users.

A cookie is a small text file that lets you store a small amount of data (nearly 4KB) on the user’s computer. They are typically used to keeping track of information such as a username that the site can retrieve to personalize the page when a user visits the website next time.


Create cookies with PHP

Setting a cookie requires a key, a value, and the amount of time to allow the cookie to exist.

Setting cookie
      $first_name = 'Anwar';
      setcookie('first_name',$first_name,time() + (86400 * 7)); // 86400 = 1 day


Use $_COOKIE to retrieve a cookie with PHP. Once the cookies have been set, they can be accessed on the next page load.

Retrieve a cookie
       if(!isset($_COOKIE['first_name'])) {
    	    echo 'Cookie does not exist...';
       } else {
	    echo 'Cookie value is: ' . $_COOKIE['first_name'];


Cookies are set to be deleted when the browser is closed. We can override that default by setting a time for the cookie’s expiration.┬áJust use setcookie with an expiration date in the past, to trigger the removal mechanism in your browser.

      setcookie("first_name", "$first_name", time()-60);



Store username/password information so that the user doesn’t have to log in every time they visit the website.
Remember the user’s name.
Keep track of a user’s progress during a specified process.

Anwar Yakkiparamban

Anwar Yakkiparamban is the founder of Lauyou Learning. Prior to Lauyou learning, Anwar worked at ARD Engineering & Development, Qatar. He holds bachelor degree in Electronics and Communication Engineering from Govt. Engineering College Idukki.

You may also like...