Job with Cookies on PHP
Introduction:
Whence there was a term "cookie" anybody authentically does not know, though it is considered, that in days of origin of Unix-systems word-combination Magic Cookies somewhere was used. "Receipts" (token, ticket) which programs exchanged meant.
Cookie is the decision of one of hereditary problems HTTP of the report (HyperText Transfer Protocol). This problem consists in inconstancy of connection between the client and the server as at FTP or Telnet sessions, i.e. for each document (or a file) by transfer on HTTP the separate search it is sent the report. Inclusion cookie in HTTP the report has given the partial decision of this problem. In other words, transaction comes to the end after the browser has queried, and the server has given out the corresponding answer. Right after it the server "overlooks" about the user and each following search of the same user counts the new user.
Using cookie, it is possible to emulate session on HTTP to the report. Shortly the principle of emulation of session is those: on the first search it is given out sootvestvujuhhee value cookie, and at each subsequent search this value is read from a variable of environment HTTP_COOKIE and in appropriate way processed.
Simple example: there is a form where the user is offered to specify the name, from it{her} the script registering value cookie in a browser of the user is caused. At each subsequent call on the basis of the analysis of value cookie from a browser of the user on page there is or a nominal greeting (if there is an established value cookie), or an initial form with search of a login name (if value cookie is not established).
So, we shall start practice:
1. The task cookie with help PHP
For the task of this finkcii in language php there is an operator:
setcookie (). The most pleasant, that function setcookie () perceives up to six arguments, how you are going to to operate values cookie and who will read out its{her} values.
The elementary way to establish cookie is those:
setcookie (' name ',' bret ');
Then, for each subsequent page on your site, prosmatrivaemoj during the given session (while the user will not leave a site) the variable $name will matter ' bret ' and it{he} can be read easily means PHP. This type cookie is known as cookie-session as value is saved during the user session.
If you want, that value cookie was remembered by a browser after the user will finish session, you should pass functions setcookie () the third parameter - an expiration date of action cookie. As PHP it was generated basically in Unix environment, you should present time of expiry of the term of action cookie as number of the seconds past{last} since January, 1, 1970 If you have experience of programming for Unix, it will not seem to you surprising. But, if you programmed only in Windows environment or Macintosh, you, maybe, are surprised, that for cranky people these Unix-oidy.
But be not afraid. PHP has very convenient function, mktime (). You specify to her as parameters (in that order) hour, minute, second, month, day and the year specifying that moment of time which you would like to introduce in perceived UNIX a format, and mktime () returns to you number of the seconds past{last} since January, 1, 1970 till the specified moment of time. For example, if you want, that validity cookie has expired on January, 1, 2000, you write down:
<? php
$y2k = mktime (0,0,0,1,1,2000);
setcookie (' name ',' bret ', $y2k);
?>
If you want to change value cookie on new, you can simply copy it (her ?) value. Thus, even if the browser already sent value cookie to the server on one of the previous pages, it is quite possible to inform the server, that actually you call "jeff".
<? php
$y2k = mktime (0,0,0,1,1,2000);
setcookie (' name ',' jeff ', $y2k);
?>
Pay attention to that thus value of a variable $name does not vary. It is established at loading page. If you want that value of a variable changed synchronously with change of value cookie, you should change a code as follows:
<? php
$name = ' jeff ';
$y2k = mktime (0,0,0,1,1,2000);
setcookie (' name ', $name, $y2k);
?>
The following of function of two parameters setcookie () allow you to set a way and a domain name of the one who can read value of yours cookie. By default only the pages located in the same catalogue or are lower in structure of subdirectories of that server which has established cookie, can read it (her ??) value. It is done{made} of reasons of safety. However, if at your server two domain names: "www.domain.com" i "other.domain.com", and you ehkaunt allows you to serve pages from the catalogue ~/myhome, you should cause function setcookie () as follows:
setcookie (' name ',' jeff ', $y2k, ' ~/myhome ', '.domain.com ');
Last parameter of function setcookie () which we never used, demands, that value cookie was passed only to those of the Web-server, which ispol`ujut the safe report of connection, such as SSL. If it is necessary for you, set for the sixth parameter value 1.
To remove cookie too it is very simple, to pass functions setcookie () a name cookie enough and PHP will make the everything else:
setcookie (' name ');
In summary it is necessary to make one more remark concerning use cookie. How processing cookies in report HTTP is organized, it is necessary to establish values of all cookie up to a conclusion of any text. If to make on the contrary, PHP will give out to you the prevention{warning} and value cookie it will not be sent. So it is correct:
<? php
setcookie (' name ',' jeff ');
echo " Hello Everyone! ";
?>
And so - no:
<? php
echo " Hello Everyone! ";
setcookie (' name ',' jeff ');
?>
2. The task cookie with help JavaScript
It is possible to set value cookie, using language JavaScript. Unique lack of this way consists what not all browsers of it support. The examples of functions JavaScript written by Alexey Aleksandrovym for a script "Organizer" are below resulted.
Example. Function of installation of value cookie
// name - a name cookie
// value - value cookie
// [expires] - a date closed of action cookie (by default - up to the end of session)
// [path] - a way for which cookie it is valid (by default - the document in which value has been established)
// [domain] - the domain for which cookie it is valid (by default - the domain in which value has been established)
// [secure] - logic value, whether showing is required the protected transfer of value cookie
function setCookie (name, value, expires, path, domain, secure) {
var curCookie = name + "=" + escape (value) +
((expires)? "; expires = " + expires.toGMTString (): " ") +
((path)? "; path = " + path: " ") +
((domain)? "; domain = " + domain: " ") +
((secure)? "; secure ": " ")
if (! caution || (name + "=" + escape (value)) .length <= 4000)
document.cookie = curCookie
else
if (confirm (" Cookie exceeds 4KB and it will be cut out! "))
document.cookie = curCookie
}
Example. Function of reading of value cookie
Returns the established value or an empty line if cookie does not exist.
// name - a name read - out cookie
function getCookie (name) {
var prefix = name + "="
var cookieStartIndex = document.cookie.indexOf (prefix)
if (cookieStartIndex ==-1)
return null
var cookieEndIndex = document.cookie.indexOf (";", cookieStartIndex + prefix.length)
if (cookieEndIndex ==-1)
cookieEndIndex = document.cookie.length
return unescape (document.cookie.substring (cookieStartIndex + prefix.length, cookieEndIndex))
}
Example. Function of removal{distance} of value cookie
The principle of job of this function consists that cookie is established with obviously out-of-date parameter expires, in this case on January, 1, 1970.
// name - a name cookie
// [path] - a way for which cookie it is valid
// [domain] - the domain for which cookie it is valid
function deleteCookie (name, path, domain) {
if (getCookie (name)) {
document.cookie = name + "=" +
((path)? "; path = " + path: " ") +
((domain)? "; domain = " + domain: " ") +
"; expires=Thu, 01-Jan-70 00:00:01 GMT "
}
3. The task cookie with help Perl
The most powerful and floppy way of management of documents with use of the mechanism cookie - with the help of CGI-scripts. The task of value cookie on Perl will look as follows:
print " Content-type: text/html\n ";
print " Set-Cookie: username=aaa13; expires=Friday, 31-Dec-99 23:59:59 GMT; path =/; domain=www.citforum.ru; \n\n ";
The script at delivery of results of job generates HTTP heading:
Content-type: text/html
Set-Cookie: « username=aaa13; expires=Friday, 31-Dec-99 23:59:59 GMT; path =/; domain=www.webscript.ru; »
To read in a script earlier a preset value cookie, the variable of environment HTTP_COOKIE is used.
$cookie = $ENV {' HTTP_COOKIE '};
Further it is possible to analyze the received line and, depending on the read out values, to carry out corresponding actions.
And now about grusnom...
Restrictions:
The client (browser) has the following restrictions for cookies:
? All it can be stored{kept} up to 300 values cookies
? Everyone cookie cannot exceed 4Kbajt
? From one server or the domain it can be stored{kept} up to 20 values cookie
If restriction 300 or 20 is exceeded, the first recording on time leaves. At excess of a limit of volume in 4Kbajt the correctness of value cookie suffers - otrezaetsja a piece of recording (from the beginning of this recording) equal to excess of volume.
In case of caching documents, for example, the proxy-server, field Set-cookie HTTP of heading never kehshiruetsja.
If the proxy-server accepts the answer containing field Set-cookie in heading, it is supposed, that the field reaches the client without dependence from a return code 304 (Not Modified) or 200 (OK). Accordingly, if the client search contains in heading Cookie he should reach the server even if parameter If-modified-since is rigidly established.
That's all, success!

|