Introducing Cookies

Introducing Cookies
You can use cookies within your PHP scripts to store small bits of information about a user. A cookie is a small amount of data stored by the user’s browser in compliance with a request from a server or script.

ارایه درگاه پرداخت ePayBank.ir برای وب مستران ایرانی جهت دریافت وجه بصورت اینترنتی

تبلیغات نیازمندی را میتوانید براحتی با عضویت در MyCityAd.ir درج آگهی نمایید.

خرید بسته آموزش اختصاصی و کاربردی برنامه نویسی طراحی سایت mortezasaheb.irA single host can request that up to 20 cookies be stored by a user’s browser. Each cookie consists of a name, value, and expiration date, as well as host and path information. The size of an individual cookie is limited to 4KB.

After a cookie is set, only the originating host can read the data, ensuring that the user’s privacy is respected. Furthermore, the user can configure her browser to notify her upon receipt of all cookies, or even to refuse all cookie requests. For this reason, cookies should be used in moderation and should not be relied on as an essential element of an environment design without first warning the user.

The Anatomy of a Cookie
A PHP script that sets a cookie might send headers that look something like this:

HTTP/1.1 200 OK
Date: Tue, 07 May 2006 13:39:58 GMT
Server: Apache/2.0.58 (Unix) PHP/5.1.4
X-Powered-By: PHP/5.1.4
Set-Cookie: vegetable=artichoke; path=/; domain=yourdomain.com
Connection: close
Content-Type: text/html

As you can see, this Set-Cookie header contains a name/value pair, a path, and a domain. If set, the expiration field provides the date at which the browser should “forget” the value of the cookie. If no expiration date is set, the cookie expires when the user’s session expiresthat is, when he closes his browser.

The path and domain fields work together, as the path is a directory found on the domain, below which the cookie should be sent back to the server. If the path is “/”, which is common, that means the cookie can be read by any files below the document root. If the path were “/products/”, the cookie could be read only by files within the /products directory of the website.

The domain field represents that Internet domain from which cookie-based communication is allowed. For example, if your domain is www.yourdomain.com and you use www.yourdomain.com as the domain value for the cookie, the cookie will be valid only when browsing the www.domain.com website. This could pose a problem if you send the user to some domain like www2.domain.com or billing.domain.com within the course of his browsing experience because the original cookie will no longer work. Thus, it is common to simply begin the value of the domain slot in cookie definitions with a dot, leaving off the host, for example, .domain.com. In this manner, the cookie will be valid for all hosts on the domain. The domain cannot be different from the domain from which the cookie was sent; otherwise, the cookie will not function properly, if at all, or the web browser will refuse the cookie in its entirety.

If your web browser is configured to store cookies, it keeps the cookie-based information until the expiration date. If the user points the browser at any page that matches the path and domain of the cookie, it will resend the cookie to the server. The browser’s headers might look something like this:

GET / HTTP/1.0
Connection: Keep-Alive
User-Agent: Mozilla/5.0 (Windows; U; Win98; it; rv:1.8.0.1) Gecko/20060111
Firefox/1.5.0.1
Host: www.yourdomain.com
Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, image/png, */*
Accept-Encoding: gzip
Accept-Language: en, pdf
Accept-Charset: iso-8859-1, *, utf-8
Cookie: vegetable=artichoke

A PHP script will then have access to the cookie in the environment variable HTTP_COOKIE or as part of the $_COOKIE superglobal variable, which you may access three different ways:

echo $_SERVER["HTTP_COOKIE"]; // will print “vegetable=artichoke”
echo getenv(“HTTP_COOKIE”); // will print “vegetable=artichoke”
echo $_COOKIE["vegetable"]; // will print “artichoke”

Setting a Cookie with PHP
You can set a cookie in a PHP script in two ways. First, you could use the header() function to set the Set-Cookie header. The header() function requires a string that will then be included in the header section of the server response. Because headers are sent automatically for you, header() must be called before any output at all is sent to the browser:

header (“Set-Cookie: vegetable=artichoke; expires=Tue, 07-Mar-06 14:39:58 GMT;
path=/; domain=yourdomain.com”);

Although not difficult, this method of setting a cookie would require you to build a function to construct the header string. Although formatting the date as in this example and URL-encoding the name/value pair would not be a particularly arduous task, it would be a repetitive one because PHP provides a function that does just thatsetcookie().

The setcookie() function does what its name suggestsit outputs a Set-Cookie header. For this reason, it should be called before any other content is sent to the browser. The function accepts the cookie name, cookie value, expiration date in UNIX epoch format, path, domain, and integer that should be set to 1 if the cookie is only to be sent over a secure connection. All arguments to this function are optional apart from the first (cookie name) parameter.

Listing 12.1 uses setcookie() to set a cookie.

Listing 12.1. Setting and Printing a Cookie Value
1: <?php
2: setcookie(“vegetable”, “artichoke”, time()+3600, “/”, “.yourdomain.com”, 0);
3:
4: if (isset($_COOKIE["vegetable"])) {
5: echo “<p>Hello again, you have chosen: “.$_COOKIE["vegetable"].”.</p>”;
6: } else {
7: echo “<p>Hello you. This may be your first visit.</p>”;
8: }
9: ?>

Even though we set the cookie (line 2) when the script is run for the first time, the $_COOKIE["vegetable"] variable will not be created at this point. Because a cookie is read only when the browser sends it to the server, we won’t be able to read it until the user revisits a page within this domain.

We set the cookie name to “vegetable” on line 2 and the cookie value to “artichoke”. We use the time() function to get the current time stamp and add 3600 to it (there are 3,600 seconds in an hour). This total represents our expiration date. We define a path of “/”, which means that a cookie should be sent for any page within our server environment. We set the domain argument to “.yourdomain.com” (you should make the change relevant to your own domain or use localhost), which means that a cookie will be sent to any server in that group. Finally, we pass 0 to setcookie(), signaling that cookies can be sent in an insecure environment.

Passing setcookie() an empty string (“”) for string arguments or 0 for integer fields causes these arguments to be skipped.

By the Way

With using a dynamically created expiration time in a cookie, as in Listing 12.1, note the expiration time is created by adding a certain number of seconds to the current system time of the machine running Apache and PHP. If this system clock is not accurate, it is possible that it may send in the cookie an expiration time that has already passed.

You can view your cookies in most modern web browsers. Figure 12.1 shows the cookie information stored for Listing 12.1. The cookie name, content, and expiration date appear as expected; the domain name will differ when you run this script on your own domain.

Figure 12.1. Viewing a stored cookie in a web browser.

For more information on using cookies, and the setcookie() function in particular, see the PHP Manual entry at http://www.php.net/setcookie.

Deleting a Cookie
Officially, to delete a cookie, you call setcookie() with the name argument only: setcookie(“vegetable”);

This approach does not always work well, however, and should not be relied on. Instead, to delete a cookie, it is safest to set the cookie with a date you are sure has already expired:

setcookie(“vegetable”, “”, time()-60, “/”, “webdesign.epaybank.ir”, 0);

Also make sure that you pass setcookie() the same path, domain, and secure parameters as you did when originally setting the cookie.