Recipe 8.2. Reading Cookie Values

8.2.1. Problem

You want to read the value of a cookie that you've previously set.

8.2.2. Solution

Look in the $_COOKIE auto-global array, as shown in Example 8-5.

Reading a cookie value

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

8.2.3. 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 sent back to the server 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, as in Example 8-6.

Reading all cookie values

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

8.2.4. See Also

Recipe 8.1 shows how to set cookies; Recipe 8.3 shows how to delete cookies; Recipe 8.12 explains output buffering; Recipe 9.15 for information on register_globals.

PHP Cookbook, 2nd Edition
PHP Cookbook: Solutions and Examples for PHP Programmers
ISBN: 0596101015
EAN: 2147483647
Year: 2006
Pages: 445

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: