Home >> FAQs/Tutorials >> PHP Script Tutorials and Tips >> Index

PHP Script Tips - Understanding and Managing Cookies

By: FYICenter.com

Part:   1  2  3  4  5  6   7 

(Continued from previous part...)

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.

(Continued on next part...)

Part:   1  2  3  4  5  6   7 


Selected Developer Jobs:

More...