start learning
Image 1

Superglobal $_COOKIE in PHP

In PHP, $_COOKIE is a superglobal variable used to access and manage cookies sent by a web browser to the server. Cookies are small pieces of data that can be stored on a user's computer and are sent back to the server with each subsequent HTTP request. $_COOKIE allows PHP scripts to access and manipulate these cookies, enabling the storage of user-specific information across different sessions.


Example with Clarification :

Let's create an example to illustrate how to use the $_COOKIE superglobal to set and retrieve cookies in PHP.

<?php
// Set a cookie with a name "user" and value "JohnDoe"
setcookie("user", "JohnDoe", time() + 3600, "/");
?>
<!DOCTYPE html>
<html>
<head>
    <title>PHP $_COOKIE Superglobal Example</title>
</head>
<body>
    <h1>Cookie Example </h1>
      <p>A cookie named "user" has been set with the value "JohnDoe".</p>
</body>
</html>

  1. We use the setcookie() function to set a cookie named "user" with the value "JohnDoe."
  2. The time() + 3600 parameter sets the cookie to expire after one hour.
  3. The "/" path parameter makes the cookie accessible from the root of the domain.
Retrieving a Cookie :

Now, let's create another PHP script to retrieve and display the "user" cookie :

<!DOCTYPE html>
<html>
<head>
    <title>PHP $_COOKIE Superglobal Example</title>
</head>
<body>
    <h1>Cookie Retrieval Example</h1>
<?php
    if (isset($_COOKIE['user'])) {
        $user = $_COOKIE['user'];
        echo "<p>Welcome back, $user!</p>";
    } else {
        echo "<p>Cookies are not set or have expired.</p>";
    }
?>
</body>
</html>
  1. In this PHP script, we check if the "user" cookie exists using isset($_COOKIE['user']).
  2. If the cookie exists, we retrieve its value with $_COOKIE['user'].
  3. We then display a personalized message to the user.
  4. If the cookie doesn't exist or has expired, we display a message indicating that cookies are not set or have expired.

This example demonstrates how to set and retrieve cookies using the $_COOKIE superglobal. It's a fundamental mechanism for storing and retrieving user-specific data in PHP applications, like user authentication tokens or user preferences. Keep in mind that cookie values are stored on the user's computer, and sensitive information should not be stored directly in cookies for security reasons.