PHP Cookies (original) (raw)

Last Updated : 31 May, 2025

A cookie is a small text file that is stored in the user's browser. Cookies are used to store information that can be retrieved later, making them ideal for scenarios where you need to remember user preferences, such as:

Cookies in PHP are created using the setcookie() function. When a cookie is set, the data is stored in the user’s browser and sent to the server with each subsequent request made by the browser.

**Syntax:

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

**In this syntax:

How Do Cookies Work?

Cookies work in the following ways:

How to Use Cookies in PHP?

**1. Creating Cookies

Create a cookie named Auction_Item and assign the value Luxury Car to it. The cookie will expire after 2 days(2 days * 24 hours * 60 mins * 60 seconds).

**Example: This example describes the creation of the cookie in PHP.

PHP `

Note: You might have to reload the page to see the value of the cookie.

`

**Note: Only the name argument in the setcookie() function is mandatory. To skip an argument, the argument can be replaced by an empty string("").

**Output:

Cookie creation in PHP

**In this example:

It is always advisable to check whether a cookie is set or not before accessing its value. Therefore, to check whether a cookie is set or not, the PHP isset() function is used. To check whether a cookie "Auction_Item" is set or not, the isset() function is executed as follows:

**Example: This example describes checking whether the cookie is set or not.

PHP `

Note: You might have to reload the page to see the value of the cookie.

`

**Output:

Checking for the cookie to be set

**In this example:

For accessing a cookie value, the PHP $_COOKIE superglobal variable is used. It is an associative array that contains a record of all the cookies values sent by the browser in the current request. The records are stored as a list where the cookie name is used as the key. To access a cookie named "Auction_Item", the following code can be executed.

**Example: This example describes accessing & modifying the cookie value.

PHP `

Note: You might have to reload the page to see the value of the cookie.

`

**Output:

Accessing the Cookie value

**In this example:

**4. Deleting Cookies

The setcookie() function can be used to delete a cookie. For deleting a cookie, the setcookie() function is called by passing the cookie name and other arguments or empty strings, however, this time, the expiration date is required to be set in the past. To delete a cookie named "Auction_Item", the following code can be executed.

**Example: This example describes the deletion of the cookie value.

PHP `

Note: You might have to reload the page to see the value of the cookie.

`

**Output:

Deleting the Cookie

**In this example:

Use Cases for Cookies

Cookies are used in various scenarios, including:

2, "item2" => 1]); setcookie("cart", $cart, time() + 3600, "/"); ?>