Getting Cookies


After you set a cookie, it won't be visible to your scripts until the next time you load a page. That's because the cookie is sent to the server from the user's machine, so immediately after you set a cookie, you won't be able to read it; you need to get a page back from the browser first. Note also that cookies are sent in the HTTP headers in pages sent to you by the browser, and if your cookie-handling page is in domain A (such as www.ultragiantbigco.com), only the cookies that came from domain A are sent to you.

After the cookies have been set, they can be accessed on the next page load with the $_COOKIE array. We set a cookie named message in the previous chunkso now we'll read it here. The values of cookies are automatically loaded into the global array $_COOKIES, much like how the values of web page data are stored in $_REQUEST.

To read the text from the message cookie, we'll check $_COOKIE['message']. If that variable is set, some cookie data is waiting for us:

 <?php     if (isset($_COOKIE['message'])) {         .         .         .     } ?> 

In this case, we'll just echo the recovered data from the cookie to the browser's window:

 <?php     if (isset($_COOKIE['message'])) {         echo $_COOKIE['message'];     } ?> 

You can see how this works in Example 9-2, phpgetcookie.php.

Example 9-2. Reading a cookie, phpgetcookie.php
 <HTML>     <HEAD><TITLE>             Getting a cookie         </TITLE></HEAD>     <BODY><CENTER>             <H1>Getting a cookie</H1>             The cookie says:             <?php                 if (isset($_COOKIE['message'])) {                     echo $_COOKIE['message'];                 }             ?>          </CENTER><BODY> </HTML> 

After setting the cookie with phpsetcookie.php, you can navigate to phpgetcookie.php, as you see in Figure 9-2, to read the data from the cookie. Very cool.

Figure 9-2. Reading a cookie.


Cookies names can also be set as array names and will be available to your PHP scripts as arrays. For example, if you did this:

 setcookie("cookie[one]", "No"); setcookie("cookie[two]", "worries"); setcookie("cookie[three]", "today."); 

Then after these cookies have been set, you could read them next time the browser sends you a page like this:

 if (isset($_COOKIE['cookie'])) {     foreach ($_COOKIE['cookie'] as $data) {         echo "$value <BR>";     } } 

Now you've got the ability to set and retrieve cookies. Not bad.



    Spring Into PHP 5
    Spring Into PHP 5
    ISBN: 0131498622
    EAN: 2147483647
    Year: 2006
    Pages: 254

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net