Current Location: Home> Latest Articles> How to Create, Read, and Delete Cookies in PHP

How to Create, Read, and Delete Cookies in PHP

gitbox 2025-07-29

How to Create, Read, and Delete Cookies in PHP

In web development, cookies are commonly used to store user information and maintain user states. For instance, users can stay logged in even without having to log in again on subsequent visits by setting a cookie that contains login information. This article will guide you through creating, reading, and deleting cookies in PHP.

Creating a Cookie

Creating cookies in PHP is straightforward with the setcookie() function. The basic usage is as follows:

setcookie('name', 'value', time() + 3600, '/');

This example demonstrates how to create a cookie named "name" with the value "value", an expiration time of one hour, and a path scope of the website root directory.

The setcookie() function parameters are as follows:

  • $name: The name of the cookie.
  • $value: The value of the cookie.
  • $expires: The expiration time of the cookie. If not set, it will expire at the end of the session.
  • $path: The path for which the cookie is valid. The default is "/".
  • $domain: The domain for which the cookie is valid. The default is the current domain.
  • $secure: Whether to send the cookie only over HTTPS connections. The default is false.
  • $httponly: Whether the cookie can only be accessed via HTTP, not JavaScript. The default is false.

Reading a Cookie

To read cookies in PHP, you can access the global variable $_COOKIE. This variable is an array that contains all the cookies sent with the current request.

Here is an example of how to read a cookie:

if (isset($_COOKIE['name'])) {
    $value = $_COOKIE['name'];
    echo $value;
} else {
    echo 'Cookie not set!';
}

This code checks whether a cookie with the name "name" exists. If it does, it outputs its value; otherwise, it prints "Cookie not set!".

Deleting a Cookie

To delete a cookie in PHP, you simply set its expiration time to a timestamp in the past.

Here is an example of deleting a cookie:

setcookie('name', '', time() - 3600, '/');

This code deletes the cookie named "name" by setting its expiration time to one hour ago.

In summary, creating, reading, and deleting cookies in PHP is simple. Developers can set different cookie parameters such as expiration time, path, and scope according to their needs. When using cookies, it's essential to ensure privacy protection and avoid leaking sensitive information.