Friday, 2010-07-30

Who's Online

We have 7 guests online


Breadcrumbs

Home Cookies


Cookies PHP
Cookies

                                PHP Cookies

For those new to web development and 'how things work', cookies can be a very confusing matter.I will give you an overview of cookies to help you understand how they work.

  • What is a Cookie?

A cookie is often used to identify a user. A cookie is a small file that the server embeds on the user's computer. Each time the same computer requests a page with a browser, it will send the cookie too. With PHP, you can both create and retrieve cookie values.

The size of a cookie depends on the browser but in general should not exceed 1K (1,024 bytes). The information can really be anything... it can be a name, the number of visits to the site, web based shopping cart information, personal viewing preferences or anything else that can be used to help provide customized content to the user.

In addition to the information it stores, each cookie has a set of attributes: an expiration date, a valid domain, a valid domain path and an optional security flag. These attributes help ensure the browser sends the correct cookie when a request is made to a server.

 

  • How to Create a Cookie?


When you create a cookie, using the function setcookie, you must specify three arguments.

These arguments are setcookie(name, value, expiration):

 

     1.  name: The name of your cookie. You will use this name to later retrieve your cookie, so don't forget it!

     2.  value: The value that is stored in your cookie. Common values are username(string) and last visit(date).

     3.  expiration: The date when the cookie will expire and be deleted. If you do not set this expiration date, then it will be treated as

          a session cookie and be removed when the browser is restarted.

     4.  $path - path on the server where cookie will be available.

          For example, if the path is set to "/", the cookie will be available through out the whole site. If the cookie is set to say "/news/",

          the cookie will only be available under /news/ and all its sub-directories.

          If no path is given, cookie in created under the current directory.

     5.  $domain - domain where cookie will be available. Instead of path you can use domain settings.

          For example, if the domian is set to ".yourdomian.com", the cookie will be available within the domain nd all its sub-domains, example

          news.yourdomain.com.

          If the cookie is set say "www.yourdomian.com" the cookie will be available under all www sub-domains, example

          " www.yourdomian.com/news"

     6.  $secure - true if cookie is being set over a secure "https" server, false otherwise, Default value is false.

 

Here's a small reference on numbers and the amount of time they signify in determining the expiration date/time of a cookie:

 
 
                                One Minute: 60
                                Ten Minutes: 600
                                Half-an-Hour: 1800
                                One Hour: 3600
                                One Day: 86400
                                One Week: 604800
                                Two Weeks: 1209600
                                One Month (30 days): 2592000
                                One Year (365 days): 31536000

 

You can probably work with these numbers to determine how many seconds are in any given amount of time. Be sure to have a calculator handy, though! If you lack a real-life calculator, Windows users can click on their Start Menu, choose "Run", and type in "calc." You can use comments after the setcookie() command, i personally think that is a good idea to remember after how long the cookies will expire

 

The setcookie() function is used to set a cookie.

Note: The setcookie() function must appear BEFORE the <html> tag.

Syntax:

                                                      setcookie(name, value, expire, path, domain);

 

Example 1:

In the example below, we will create a cookie named "user" and assign the value "Jimmy Hendrix" to it.

We also specify that the cookie should expire after one hour:

Code:

                                                      <?php
                                                      setcookie("user", "Jimmy Hendrix", time()+3600);       // expire in one our
                                                      ?>

                                                      <html>
                                                      .....

 

Note:  The value of the cookie is automatically URLencoded when sending the cookie, and automatically decoded when received (to prevent URLencoding, use setrawcookie() instead).

 

Example 2:

You can also set the expiration time of the cookie in another way. It may be easier than using seconds.

Code:

                                                       <?php
                                                       $expire=time()+60*60*24*30;                  // expire in one month
                                                       setcookie("user", "Jimmy Hendrix", $expire);
                                                       ?>

                                                       <html>
                                                       .....

 

In the example above the expiration time is set to a month (60 sec * 60 min * 24 hours * 30 days).

 

  • How to Retrieve a Cookie Value?

The PHP $_COOKIE variable is used to retrieve a cookie value.

In the example below, we retrieve the value of the cookie named "user" and display it on a page:

Code:

                                                         <?php
                                                         // Print a cookie
                                                                   echo $_COOKIE["user"];

                                                         // A way to view all cookies
                                                                   print_r($_COOKIE);
                                                         ?>

 

 

In the following example we use the isset() function to find out if a cookie has been set:

Code:

                                                          <html>
                                                          <body>

                                                          <?php
                                                                    if (isset($_COOKIE["user"]))
                                                                       echo "Welcome " . $_COOKIE["user"] . "!<br />";
                                                                    else
                                                                       echo "Welcome guest!<br />";
                                                          ?>

                                                          </body>
                                                          </html>

 

 

  • How to Delete a Cookie?

When deleting a cookie you should assure that the expiration date is in the past.

Delete example:

Code:

                                                           <?php
                                                           setcookie("user", "", time()-3600);                // set the expiration date to one hour ago
                                                           ?>

 

 

  • What if a Browser Does NOT Support Cookies?

If your application deals with browsers that do not support cookies, you will have to use other methods to pass information from one page to another in your application. One method is to pass the data through forms (forms and user input are described earlier in this tutorial).

The form below passes the user input to "welcome.php" when the user clicks on the "Submit" button:

Code:

                                                            <html>
                                                            <body>

                                                            <form action="welcome.php" method="post">
                                                                     Name: <input type="text" name="name" />
                                                                     Age:   <input type="text" name="age" />
                                                                               <input type="submit" />
                                                            </form>

                                                            </body>
                                                            </html>

 

 

Retrieve the values in the "welcome.php" file like this:

Code:

                                                             <html>
                                                             <body>

                                                             Welcome <?php echo $_POST["name"]; ?>.<br />
                                                             You are <?php echo $_POST["age"]; ?> years old.

                                                             </body>
                                                             </html>