Setting a Cookie s Expiration Time


Setting a Cookie's Expiration Time

There's more to setcookie than simply setting a cookie's text value. You can also specify how long the cookie should exist on the user's machine. If you don't, the cookie will be deleted when the user ends the current browser session (which usually means closing all browser windows). But you can specify how long a cookie should last by giving a value for the expire parameter in setcookie:

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

The time stored in this parameter is a Unix timestamp, holding the number of seconds since January 1st, 1970, and specifying the time when the cookie should be deleted. To get the current number of seconds since January 1st, 1970, you can use the PHP time function. For example, to specify that a cookie should be deleted in an hour, you can do something like this, where you specify an expiration time of time() + 3600 seconds:

 <?php     setcookie("mycookie", $value, time() + 3600); ?> 

We'll create a cookie in phpsetconfiguredcookie.php, which will last 30 days and hold the text "No worries for 30 days." as you can see in Example 9-3.

Example 9-3. Setting a timed cookie, phpsetconfiguredcookie.php
 <?php     setcookie("message", "No worries for 30 days.", time()+60*60*24*30); ?> <HTML>     <HEAD>         <TITLE>             Setting a configured cookie         </TITLE>     </HEAD>     <BODY>         <CENTER>             <H1>Setting a configured cookie</H1>             Cookie has been set to expire in 30 days! Look at                <A HREF="phpgetcookie.php">phpgetcookie.php</A> next.          </CENTER>     <BODY> </HTML> 

You can see what this page looks like in Figure 9-3, where we're setting the cookie that will last 30 days (unless intentionally deleted).

Figure 9-3. Setting a timed cookie.


When you click the hyperlink in Figure 9-3, phpgetcookie.php appears, correctly showing the text of the 30-day cookie, as you see in Figure 9-4.

Figure 9-4. Getting a timed cookie.


Specifying the expiration time of a cookie is a good idea if you need a long-term cookie that should last beyond the current browser session. If you don't extend your cookie's life, it'll be deleted when the browser session ends.



    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