Setting Cookies


Cookies hold text that you can store on the user's computer and retrieve later. You can set cookies using the setcookie function:

 setcookie(string name [, string value [, int expire [, string path [, string domain [, int secure]]]]]) 

This function defines a cookie to be sent to the user's machine. Here is what the various parameters mean:

  • name. The name of the cookie.

  • value. The value of the cookie. (This value is stored on the client's computer, so you should not store sensitive information.)

  • expire. The time the cookie expires. This is the number of seconds since January 1, 1970. You'll most likely set this with the PHP time function plus the number of seconds before you want it to expire.

  • path. The path on the server on which the cookie will be available.

  • domain. The domain for which the cookie is available.

  • secure. Indicates that the cookie should only be transmitted over a secure HTTPS connection. When set to 1, the cookie will only be set if a secure connection exists. The default is 0.

Note that cookies are part of the HTTP headers sent to the browsers, and so they must be sent before any other output from your script. This means that you should place calls to this function before any other output, including <HTML> and <HEAD> tags. If some output exists before calling this function, setcookie may fail and return FALSE. If setcookie runs successfully, it will return trUEbut that does not indicate whether the user accepted the cookie.

Here's an example. In this case, we're going to create a cookie named message that will hold the text "No worries.", and we do that with setcookie:

 <?php     setcookie("message", "No worries."); ?> 

This PHP goes at the beginning of the script phpsetcookie.php, as you can see in Example 9-1.

Example 9-1. Setting a cookie, phpsetcookie.php
 <?php     setcookie("message", "No worries."); ?> <HTML>     <HEAD>         <TITLE>             Setting a cookie         </TITLE>     </HEAD>     <BODY>         <CENTER>             <H1>                 Setting a cookie             </H1>             Cookie has been set! Look at                <A HREF="phpgetcookie.php">phpgetcookie.php</A> next.          </CENTER>     <BODY> </HTML> 

This page appears in Figure 9-1, where PHP has sent the cookie to the browser, and it's already been set.

Figure 9-1. Setting a cookie.


Now the cookie's been set, but how do we read it? When the user clicks the hyperlink in this page, he or she will be redirected to phpgetcookie.php, which is coming up in the next chunk.



    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