CodeBlanks Logo Icon CodeBlanks

Reading cookies with $_COOKIE

PHP course · Intermediate · Lesson 89/115

Learn to read cookies sent by the browser with the $_COOKIE superglobal.

The $_COOKIE superglobal

After a cookie is created with setcookie(), the browser stores it. On the next request the browser sends it back; PHP fills the $_COOKIE superglobal with this data.

Each cookie name becomes a key: $_COOKIE['lang']. You can also iterate it as an array.

Important: in the same request where setcookie() is called, the cookie is not yet in $_COOKIE; you wait for the browser to send it back.

Checking a cookie with isset

A cookie may be undefined: the browser may not have sent it yet, or may have deleted it. Reading $_COOKIE['theme'] directly raises a warning in PHP 8.

First check the key with isset($_COOKIE['theme']). If true, read safely; if false, use a default value.

Tip: $_COOKIE['theme'] ?? 'light' gives both the check and a default in one line.

Exercise Read a default theme from a missing cookie

With if/else, check isset($_COOKIE['theme']): if defined, assign $_COOKIE['theme'] to $theme; otherwise assign 'light'. Then echo $theme.

Show example solution
Use if(isset($_COOKIE['theme'])) to set $theme from the cookie, else 'light', then echo $theme.
Example solution:
<?php
// Print the default theme if $_COOKIE['theme'] is missing
if (isset($_COOKIE['theme'])) {
    $theme = $_COOKIE['theme'];
} else {
    $theme = 'light';
}
echo $theme . "\n";

Test yourself

  1. When does a cookie appear in $_COOKIE?

    • Immediately in the same request setcookie is called
    • Only when session_start is called
    • On the next request, when the browser sends the cookie back
    • After the cookie is deleted
    Show answer

    On the next request, when the browser sends the cookie back — Correct. The cookie appears in $_COOKIE only on a later request when the browser sends it back.

  2. Read the cookie value

    <?php
    $cfg = ['default' => 'light'];
    ____
    echo $theme;
    
    Show answer
    <?php
    $cfg = ['default' => 'light'];
    $theme = $_COOKIE['theme'];
    echo $theme;
    
  3. Match the cookie reading tools

    $_COOKIE['k']
    Reads the cookie value
    isset()
    Checks the key
    ?? 'default'
    Gives default if undefined
    empty()
    Checks if empty

All lessons in Intermediate