PHP

Understanding Cookies in PHP

As a matter of fact, understanding Cookies in PHP requires learning to use the setcookie() method. Cookies in PHP allow us to store a small amount of client information.

In fact, cookies are very useful in tracking users. A website may want to know the navigation behavior of its users. So, cookies help website administrators to find out which users are frequent visitors of the website. In this way, cookies help in identifying users. Also, cookies help in determining the interests and choices made by the user. Therefore, cookies store information related to user preferences.

Understanding Cookies in PHP in Request and Response
Understanding Cookies in PHP in Request and Response

At first, (1) the Web browser sends a request to the webserver. As a result, (2) the web server sends the response along with cookies to the web browser. Further requests (3) from the web browser contain cookies also.

Basically, PHP has a number of features that allow us to work with cookies. The following sections describe the methods to create, delete, and read cookies.

Create a Cookie in PHP

setcookie() method creates a cookie. It takes several parameters. However, the cookiename parameter is required which is the first parameter. All other parameters are optional which include – value, expirydate, path, domain, secure, and httponly.

In order to modify the cookie, we need to call the setcookie() method again with the same cookie name and different parameter values.

Examples for Understanding Cookies in PHP

The following example demonstrates how to create a cookie and display its information.

Another example of creating cookies is given below.

Deleting an Existing Cookie

A cookie has an expiration date. In order to delete a cookie, we need to set the expiration date again. However, this expiration date should be set to some date in the past.

The following example demonstrates how to delete a cookie.

<?php
 $cookie_name="mycookie";
 $value="A small piece of information";
 $expirydate=time()+24*60*60;

 setcookie($cookie_name, $value, $expirydate);
 echo $_COOKIE['mycookie'];

 // Deleting the cookie
 $expirydate=time()-24*60*60;
 setcookie($cookie_name, $value, $expirydate);
 echo '<br>',$_COOKIE['mycookie'];
?>

Retrieving the Value of a Cookie

PHP has a superglobal variable $_COOKIE[‘cookiename’] that we can use to retrieve the value of the cookie. Also, the cookiename represents the name of an existing cookie.


Further Reading

Examples of Array Functions in PHP

Basic Programs in PHP

Registration Form Using PDO in PHP

princites.com

You may also like...