PHP 8.5.0 Released!

$_COOKIE

(PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8)

$_COOKIECookies HTTP

Descripción

Una variable tipo array asociativo de variables pasadas al script actual a través de Cookies HTTP.

Ejemplos

Ejemplo #1 Ejemplo de $_COOKIE

<?php
echo '¡Hola ' . htmlspecialchars($_COOKIE["nombre"]) . '!';
?>

Asumiendo que la cookie "nombre" ha sido definida anteriormente

Resultado del ejemplo anterior es similar a:

¡Hola Juan!

Notas

Nota:

Esto es una 'superglobal', o variable global automática. Esto significa simplemente que esta variable está disponible en todos los contextos del script. No es necesario hacer global $variable; para acceder a ella en las funciones o los métodos.

add a note

User Contributed Notes 5 notes

up
82
kiril (at) atern (dot) us
9 years ago
To clarify the previously posted note:

Dots (.) and spaces ( ) in cookie names are being replaced with underscores (_).
up
82
k dot andris at gmail dot com
10 years ago
beware, dots (.) in cookie names are replaces by underscores (_)
up
9
rc at opelgt dot org
2 years ago
The values of $_COOKIE in general are not identic with the values in $_SERVER["HTTP_COOKIE"]!

In phpinfo() $_SERVER["HTTP_COOKIE"] shows the actual value stored in the cookie by the browser in 7bit.
In $_COOKIE is this value after a 7bit to 8bit conversion.

When all characters in $_SERVER["HTTP_COOKIE"] are in ASCII = 7bit, $_COOKIE is displayed in phpinfo(). When one single character is not in ASCII, phpinfo() shows no value!

Although in $_COOKIE is still the 8bit conversion of $_SERVER["HTTP_COOKIE"]!
The reason: the 8bit conversion alone is not enough to say what characters are meant.
For that the used character-set is necessary.

phpinfo() does not know the character-set and better says nothing.

When using $_COOKIE in a php-generated web page the environment has the info of used character-set and so the meant characters can be displayed.

Three illustrating examples
===========================
A HTML-form is used to get the content which shall be stored in a cookie named "test".

Input string in field "test": door
$_SERVER["HTTP_COOKIE"]: test=door
$_COOKIE["test"]
   displayed in phpinfo(): door
   displayed in any html page: door

Input string in field "test" (ISO-8859-1 used in form): Tür
$_SERVER["HTTP_COOKIE"]: test=T%FCr
$_COOKIE["test"]
   displayed in phpinfo(): ""
   displayed in a ISO-8859-1-html-page: Tür
   (displayed in a UTF-8-html-page: T�r)

Input string in field "test" (UTF-8 used in form): Tür
$_SERVER["HTTP_COOKIE"]: test=T%C3%BCr
$_COOKIE["test"]
   displayed in phpinfo(): ""
   displayed in a UTF-8-html-page: Tür
   (displayed in a ISO-8859-1-html-page: Tür)
up
3
user at NOSPAM dot example dot com
2 years ago
PHP replaces dots (.) with underscores (_). To find all original cookie names (and value) you can use $_SERVER['HTTP_COOKIE'].

For example to retrieve a cookie set with <?php setcookie('testing.dots', 'value'); ?> you may use:
<?php
    $cookies = explode('; ', $_SERVER['HTTP_COOKIE']);
    $allCookies = [];

    foreach($cookies as $cookie) {
        $keyAndValue = explode('=', $cookie);
        $allCookies[$keyAndValue[0]] = $keyAndValue[1];
    }

    var_dump($allCookies);
    /*
        array(1) {
            ["testing.dots"]=>
                string(5) "value"
        }
    */

    echo $allCookies['testing.dots'];
?>
up
0
jordanbardela at gmail dot com
3 days ago
<?php
$pseudo = '';
$password = '';
if (!empty($_COOKIE['pseudo'])) {
    $pseudo = $_COOKIE['pseudo'];
}
if (!empty($_COOKIE['password'])) {
    $password = $_COOKIE['password'];
}
?>
<!doctype html>
<html lang="fr">
<head>
  <meta charset="utf-8">
  <title>Formulaire persistant</title>
</head>
<body>
  <form action="authentificate.php" method="post">
    <div>
      <label for="pseudo">Nom</label><br>
      <input type="text" id="pseudo" name="pseudo" value="<?php echo htmlentities($pseudo); ?>" required>
    </div>
    <div>
      <label for="password">Mot de passe</label><br>
      <input type="password" id="password" name="password" value="<?php echo htmlentities($password); ?>" required>
      <?php if (!empty($_GET['retry'])): ?>
        <p style="color: red;">Nom ou mot de passe incorrect</p>
      <?php endif; ?>
    </div>
    <div>
      <button type="submit">Se connecter</button>
    </div>
  </form>
</body>
</html>

<?php

$pseudo   = $_POST['pseudo']   ?? '';
$password = $_POST['password'] ?? '';

$users = array(
    "jojo" => array("password" => "pass1",    "status" => "administrator"),
    "raoul" => array("password" => "pass2", "status" => "visitor"),
    "roméo" => array("password" => "pass3", "status" => "customer"),
);

function authenticate(string $pseudo, string $password, array $users): bool {
    if ($pseudo === '' || $password === '') {
        return false;
    }
    if (!isset($users[$pseudo])) {
        return false;
    }
    return $users[$pseudo]['password'] === $password;
}

if (!authenticate($pseudo, $password, $users)) {
    header('Location: persistent_form.php?retry=1');
    exit();
}

setcookie(name: "pseudo", value: $pseudo);
setcookie(name: "password", value: $password);

session_start();
$_SESSION['pseudo'] = $pseudo;
$_SESSION['status'] = $users[$pseudo]['status'];
header('Location: site.php');
?>

<?php
session_start();
$pseudo = $_SESSION['pseudo'] ?? 'Guest';
$status = $_SESSION['status'] ?? 'unknown';
if ($status === 'customer') {
    echo htmlentities($pseudo);
    echo "<br>";
    echo "<br>";
    echo "consulter, acheter";
} else if ($status === 'administrator') {
    echo htmlentities($pseudo);
    echo "<br>";
    echo "<br>";
    echo "consulter, acheter, administrer";
} else if ($status === 'visitor') {
    echo htmlentities($pseudo);
    echo "<br>";
    echo "<br>";
    echo "consulter";
} else {
    echo "acces refuse";
}
?>
To Top