PHP Cookies: Create, Modify, Delete, and Access

By Shahnail Khan Last updated : December 25, 2023

What are Cookies?

Cookies are small pieces of data that a web server sends to a user's browser to be stored and sent back with subsequent requests. They play a crucial role in maintaining user sessions, preferences, and other information across multiple pages.

Set Cookies with PHP

We can set cookies using the setcookie() function. The setcookie() function allows you to set various options for a cookie. For instance, you can specify the domain, path, and whether the cookie should be sent over a secure connection.

Syntax

The basic syntax for setting a cookie in PHP using the setcookie() function is as follows:

setcookie(name, value, expire, path, domain, secure, httponly);

Here,

  • name: The name of the cookie is like its identifier. It's what you use to refer to the cookie later when you want to retrieve or modify it. For example, you might have a cookie named "username" or "user_id."
  • value: The value of the cookie is the information you want to store. It could be a username, user ID, or any other data relevant to your application.
  • expire: The expiration time of the cookie. Every cookie has an expiration time, which determines how long the cookie will exist on the user's browser. After this time, the browser will automatically delete the cookie. You set the expiration time using the time() function along with a duration.
  • path (optional): The path on the server for which the cookie will be available. If set to "/", the cookie will be available across the entire domain.
  • domain (optional): The domain for which the cookie is available. Specify the domain without the subdomain for broader availability.
  • secure (optional): If set to true, the cookie will only be sent over secure (HTTPS) connections. [Read Also: Check whether the page is called from 'https' or 'http']
  • httponly (optional): If set to true, the cookie will only be accessible through the HTTP protocol and not through JavaScript.

Example: Set a Cookies with PHP

In PHP, you can set a cookie using the setcookie() function.

<?php
// Set a cookie named 'user' with the
// value 'SK' that expires in 1 hour
setcookie("user", "SK", time() + 900);
?>

In this example:

  • 'user' is the name of the cookie.
  • 'SK' is the value of the cookie.
  • time() + 900 sets the expiration time of the cookie. Here, it's set to expire in 30 minutes (900 seconds).

Retrieve Cookie Values with PHP

Once a cookie is set, you can retrieve its value using the $_COOKIE superglobal.

if (isset($_COOKIE['user'])) {
//Write your code here
}

The above line of code uses the isset() function to check if the cookie is set or not. The $_COOKIE variable gets the value of the cookie. If the cookie is set, its value will be displayed.

Deleting a Cookie with PHP

To delete a cookie, you can set its expiration time to a past date.

Example

<?php
// Delete the 'user' cookie
setcookie("user", "", time() - 3600);
?>

Set Expiration Time with PHP

This sets the expiration time to an hour ago, effectively deleting the cookie.

Example

Let's create a simple PHP script that sets a cookie with the user's name and then retrieves and displays it.

<?php
// Set a cookie named "user" with the
// value "Mr XYZ" that expires in 1 hour
$cookie_name = "user";
$cookie_value = "Mr XYZ";
setcookie($cookie_name, $cookie_value, time() + 3600, "/");

// expires in 1 hour
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Cookie Example</title>
</head>
<body>

<?php // Check if the cookie is set and display the user's name
if (isset($_COOKIE[$cookie_name])) {
    echo "<p>Welcome back, " . $_COOKIE[$cookie_name] . "!</p>";
} else {
    echo "<p>Cookies not set. Hello, stranger!</p>";
}
?>

</body>
</html>

Output

Welcome back, user!

Code Explanation

  • We set a cookie named "user" with the value "Mr XYZ" using the setcookie() function.
  • The cookie is set to expire in 1 hour (time() + 3600).
  • The HTML part of the script checks if the cookie is set and displays a welcome message with the user's name if it is set; otherwise, it displays a generic greeting.

When you run this script, it will create a cookie on the user's browser, and upon subsequent visits within the next hour, it will recognize the cookie and welcome the user back. After an hour, the cookie will expire, and the script will treat the user as a new visitor.

Modify a Cookie Value with PHP

To modify a cookie in PHP, you have to set the cookie again using the setcookie() function.

Check if Cookies are Enabled with PHP

There is no such function to check whether cookies are enabled or not. You can check it by testing a cookie, if the cookie is not created then the count of the $_COOKIE array will be zero. Thus, to check whether cookies are enabled or not, just check count($_COOKIE) > 0 using the conditional statement.

Example

In this PHP script, we are checking whether cookies are enabled or not.

<?php
// Set a cookie named "user" with the
// value "Mr XYZ" that expires in 1 hour
$cookie_name = "user";
$cookie_value = "Mr XYZ";
setcookie($cookie_name, $cookie_value, time() + 3600, "/");

// expires in 1 hour
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Cookie Example</title>
</head>
<body>

<?php // Check if the cookie is set and display the user's name

if (count($_COOKIE) > 0) {
    echo "<p>Cookies are enabled.</p>";
} else {
    echo "<p>Cookies are not enabled.</p>";
}
?>

</body>
</html>
Cookies are enabled.

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.