PHP Cookie Set, Get And Delete Example
Php 01-Oct-2021

PHP Cookie Set, Get And Delete Example

How to cookie set, retrieve and delete in php. In this tutorial, you will learn how to set, get and delete cookies in PHP.

And this tutorial will guide on step by step on how to create, access and delete cookies in PHP with examples.

First of all, you need to know about cookies.

What is cookie in PHP?

According to w3school, A cookie is often used to identify a user. A cookie is a small file that the server embeds on the user’s computer. Each time the same computer requests a page with a browser, it will send the cookie too. With PHP, you can both create and retrieve cookie values.

In otherwords, A cookie is a small file with the maximum size of 4KB that the web server stores on the client computer. Once a cookie has been set, all page requests that follow return the cookie name and value.

A cookie can only be read from the domain that it has been issued from. For example, a cookie set using the domain www.tutsmake.com can not be read from the domain career.tutsmake.com.

Note that, Each time the browser requests a page to the server, all the data in the cookie is automatically sent to the server within the request.

How to Set, Get And Delete Cookie In PHP

You can learn following methods with example of how to how to cookie set, get and delete in PHP:

  • Set Cookie PHP
  • Get Cookie PHP
  • Delete Cookie PHP
  • Uses of PHP cookie

Set Cookie PHP

Let’s see the basic syntax of used to set a cookie in php:

<?php
setcookie(cookie_name, cookie_value, [expiry_time], [cookie_path], [domain], [secure], [httponly]);
?>

Example of set cookie in PHP:

$first_name = 'codinghelptech.com';
setcookie('first_name',$first_name,time() + (86400 * 7)); // 86400 = 1 day

Get Cookie PHP

To retrieve the get cookie in PHP:

<?php
     print_r($_COOKIE);    //output the contents of the cookie array variable 
?>

Output of the above code will be:

Output:
 
Array ( [PHPSESSID] => h5onbf7pctbr0t68adugdp2611 [first_name] => codinghelptech.com)

If you want to get only single cookie in PHP. So, you can use the key while getting the cookie in php as follow:

echo 'Hello '.($_COOKIE['first_name']!='' ? $_COOKIE['first_name'] : 'Guest'); 

Delete Cookie PHP

If you want to destroy a cookie before its expiry time, then you set the expiry time to a time that has already passed.

<?php
 setcookie("first_name", "codinghelptech.com", time() - 360,'/');
?>

Uses of PHP cookie

  • The cookie is a file websites store in their users’ computers.
  • Cookies allow web applications to identify their users and track their activity.
  • To set cookies, PHP setcookie() is used.
  • To see whether cookies are set, use PHP isset() function.

Conclusion

How to cookie set, retrieve and delete in php. In this tutorial, you have learn how to set, get and delete cookies in PHP. And as well as uses of PHP cookies.