Skip to Content
PHP Cookbook
book

PHP Cookbook

by David Sklar, Adam Trachtenberg
November 2002
Intermediate to advanced
640 pages
16h 33m
English
O'Reilly Media, Inc.
Content preview from PHP Cookbook

8.2. Reading Cookie Values

Problem

You want to read the value of a cookie that’s been previously set.

Solution

Look in the $_COOKIE superglobal array:

if (isset($_COOKIE['flavor'])) {
    print "You ate a $_COOKIE[flavor] cookie.";
}

Discussion

A cookie’s value isn’t available in $_COOKIE during the request in which the cookie is set. In other words, the setcookie( ) function doesn’t alter the value of $_COOKIE. On subsequent requests, however, each cookie is stored in $_COOKIE. If register_globals is on, cookie values are also assigned to global variables.

When a browser sends a cookie back to the server, it sends only the value. You can’t access the cookie’s domain, path, expiration time, or secure status through $_COOKIE because the browser doesn’t send that to the server.

To print the names and values of all cookies sent in a particular request, loop through the $_COOKIE array:

foreach ($_COOKIE as $cookie_name => $cookie_value) {
    print "$cookie_name = $cookie_value<br>";
}

See Also

Recipe 8.2 shows how to set cookies; Recipe 8.4 shows how to delete cookies; Recipe 8.13 explains output buffering; Recipe 8.19 shows how to avoid the “headers already sent” error message that sometimes occurs when calling setcookie( ); Recipe 9.8 for information on register_globals.

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

PHP Cookbook

PHP Cookbook

Eric A. Mann
PHP Cookbook, 2nd Edition

PHP Cookbook, 2nd Edition

Adam Trachtenberg, David Sklar
PHP Cookbook, 3rd Edition

PHP Cookbook, 3rd Edition

David Sklar, Adam Trachtenberg
Programming PHP

Programming PHP

Rasmus Lerdorf, Kevin Tatroe

Publisher Resources

ISBN: 1565926811Supplemental ContentCatalog PageErrata