Create Retrieve Update and Remove a Cookie using PHP

Today we’ll show you how to create, retrieve, update and remove a cookie using PHP. A cookie is a small file that is stored in a user’s web browser and used for tracking users browsing activity. Maximum size of cookie is 4KB.

We can use the session in PHP to store the data at the server side whereas cookie will be used at client side.

Way to manage cookies in PHP

  1. Create cookie
  2. Retrieve cookie
  3. Update cookie
  4. Remove cookie

1. Create cookie

Use the setcookie() function, to set a cookie using PHP.

Syntax:

Let’s check an example of creating a cookie.

Here, we used the / as a path that specifies the cookie is available on all websites.

Take another example to set multiple cookies.

We have an array of user data and want to set all user data in cookies then write a code as below.

Run the following code If you want to set a cookie with an array as a value.

Note: If expiry time is set to 0, the cookie will expire when the browser closes.

2. Retrieve cookie

To retrieve the cookie, we use the $_COOKIE variable. It is an associative array that holds the all cookies value and can be retrieved as individual cookie value. We can access the cookie value on another page, once cookies have been set.

Now we have set all user data in cookie and want to retrieve username then write the following code.

3. Update cookie

To update cookie value, again we need to set a cookie value using setcookie() function.

4. Remove cookie

To remove cookie value, we can use the setcookie() function with expiry time in the past as shown below.

That’s it for today to create, retrieve, update and remove a Cookie in PHP. Hope you like it.
Thank you for reading. Happy Coding..!!

If you found value in this article,
you can support us by buying me a coffee! ☕

You may also like...

Leave a Reply

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