Cookies in PHP and their use

Source: Internet
Author: User
Tags set cookie setcookie

Cookie technology is a very controversial technology, since its inception it has become a vast number of network users and web developers
A point of contention. Some Internet users, even some senior web experts, are dissatisfied with its generation and promotion, not because
Cookie technology is too weak or other technical performance reasons, but simply because they feel the use of cookies, the privacy of network users
Poses a hazard. Because cookies are small text files saved by the Web server in the user's browser, they contain information about the user, such as identity
Identify the number, password, how users are shopping on the Web site, or how many times the user has visited the site.

So what about cookie technology? Whether it really brings personal privacy to the network users of the harm. Or let's look at the bottom of the
Let's do the answer again.

(1) Cookie Technology Introduction

In the history of Web technology, the emergence of cookie technology is a major change. The first was Netscape in its Netscape Navigator
The cookie technology was introduced into the browser, and since then the World Wide Web Association has been supporting cookie standards. And then after Microsoft's big
Force promotion (because the ASP technology used by Microsoft's IIS Web server uses cookies technology to a large extent), that is, in Microsoft's Internet
Cookie technology is fully supported in the Explorer browser. Up to now, the vast majority of browsers support cookie technology, or at least compatible cookies
Use of technology.

1 What is a cookie.

As defined in the Netscape official documentation, cookies are provided under the HTTP protocol where the server or script can maintain information on the client workstation.
One way. A Cookie is a small text file saved by a Web server in a user's browser that can contain information about a user, such as identity
Identify the number, password, how the user is shopping on the Web site, or how many times the user has visited the site. Whenever a user links to a server, the Web
The site has access to cookie information.

In layman's terms, browsers support cookies with one or more qualified files. These files are called on machines that use the Windows operating system
Make cookie files, called Magic Cookie files on Macintosh machines, which are used by Web sites to store cookie data on them.
Web sites can insert information into these cookie files, which has some side effects for some network users. Some users think this creates a personal
Privacy violations, and, worse, some people think that cookies are an encroachment on personal space and can be a security hazard to the user's computer.

Some cookies are temporary and others are ongoing. Temporary cookies only save a specified amount of time on the browser, once
The cookie will be purged by the system over the specified time. In PHP, for example, cookies are used to track user processes until the user leaves the site. Continued
Cookie is saved in the user's cookie file and can still be invoked the next time the user returns.

By saving cookies in a cookie file, some users are overly likely to think that this poses a big problem. Mainly some users are worried about cookies
It will track the habits of users surfing the web, such as what kind of sites they love, what activities they like to engage in. Fear of such personal information a
Dan fell into the hands of some ulterior motives, then the individual may become a lot of advertising garbage objects, and even the accidental damage. No
, this fear does not happen at all, because users outside the site cannot cross the site to get cookie information. So want to use this kind of eye
To apply cookies is impossible. However, some browser developers have no choice because of the mistaken understanding of some users and the "false assertion".
Choice, had to make an acquaintance of the response (for example, Netscape Navigator4.0 and Internet Explorer3.0 all provide a masking cookie for the selection
Items).

The result of this long awaited cookie technology is that it forces many browser developers to provide a flexible cookie in their browsers
Sexual control function. For example, the current two major browsers Netscape Navigator and Internet Explorer are handling cookies like this
: Netscape Navigator4.0 can not only accept cookies for warning, but also can shield off cookie;internetexplorer3.0
You can also block cookies, but you can only accept warnings in the Internet Explorer4.0 without providing masking options, but on the internet
The feature options for masking cookies are added to the updated version after Explorer4.0.

In addition, many of the latest technologies have even been able to block cookies in browsers that cannot block cookies. For example, you can pass
The cookie file is set to a different type to restrict the use of cookies. But, unfortunately, if you want to completely block cookies
Words, will certainly reject many site pages. Because many web site developers today have fallen in love with the power of cookie technology,
For example, a session object can be used without the support of cookies.

Even though there are still some Internet users arguing about cookies today, the vast majority of web users tend to Lang
Accept the cookie. Therefore, we can safely use cookie technology to develop our web pages.

2 How cookies work.

To understand cookies, it is essential to know how it works. Generally, cookies are returned via HTTP headers from the server side
to the browser. First, the server side uses the Set-cookie header in the response to create a Cookie, and then the browser in its request
The request contains this created cookie through the cookie header, and it returns to the server to complete the browser's argument.

For example, we created a cookie named login to contain the visitor's information, and when creating cookies, the header on the server side
As shown below, this assumes that the visitor's registration name is "Michael Jordan", and also that the properties of the cookie that you create are such as path,
Domain, expires and so on were specified.

Set-cookie:login=michael jordan;path=/;d omain=msn.com;
expires=monday,01-mar-99 00:00:01 GMT

The header above will automatically add a record to the cookie file in the browser-side computer. The browser names the variable "login"
The cookie is assigned "Michael Jordon". Note that the value of this cookie is passed through the UrlEncode method during the actual transfer process.
URL-coded operation. This HTTP header containing the cookie value is saved to the browser's cookie file, and the header notifies the browser
The cookie is returned to the server by a request to ignore the path, completing the authentication operation of the browser.

In addition, we use some of the cookies ' properties to qualify the cookie for use. For example, the domain property can be in the browser side of the cookie
Send to qualify, specifically to the example above, the cookie can only be the front to the designated server, and will never run to the other such as
Www.hp.com's web site up. The Expires property specifies the time period for which the cookie is saved, such as the cookie above on the browser
Save to March 1, 1999 only 1 seconds. Of course, if there are too many cookies on the browser that exceed the range allowed by the system, the browser will automatically
it for deletion. The property path is used to specify which directory path the cookie will be sent to the server.

Description: After the browser has created a cookie, for each request for the site, will be in the header with this cookie;
However, request cookies for other Web sites will never be sent along. and the browser will keep sending it until the cookie expires.

The previous section tells about the technical background of cookies, which in part explains how to set up, use, delete cookies, and cookies in PHP.
Some of the limitations. PHP support for cookies is transparent and easy to use.

1. Set Cookies

PHP uses the Setcookie function to set cookies. It is important to note that cookies are part of the HTTP protocol header and are used for browsers and
Messages between servers, you must call the cookie function before any content output that belongs to the HTML file itself. Setcookie function
Defines a cookie and attaches it to the back of the HTTP header, the prototype of the Setcookie function is as follows:

int Setcookie (string name, string value, int expire, string path,
string domain, int secure);

All parameters except name are optional. Value,path,domain three parameters can be substituted with an empty string, indicating that no
Expire and secure two parameters are numeric and can be expressed in 0. The expire parameter is a standard UNIX time tag that can be used
The time () or mktime () function is obtained in seconds. The secure parameter indicates whether this cookie is on the network via an encrypted HTTPS protocol
Transmission.

The currently set cookie does not take effect immediately, but is not visible until the next page. This is because in this page of Setup
Cookies are passed by the server to the client's browser, and the next page browser can take the cookie out of the client's machine and back to the server's original
Because Setting cookies on the same page is actually coming from the back, so if you want to delete one before inserting a new cookie, you must
Write the inserted statement first, then write the deleted statement, or you may have an expected result.

Take a look at a few examples:

Simple:

Setcookie ("MyCookie", "Value of MyCookie");

With the Expiration Time:

Setcookie ("Withexpire", "Expire in 1 Hour", Time () +3600);//3600 seconds = 1 hours

Everything:

Setcookie ("Fullcookie", "full cookie value", Time () +3600, "/forum", ". phpuser.com", 1);

Here are a few things to explain, such as your site has several different directories, then if only with no path of cookies, in a
The cookies in the pages of a directory are not visible in the pages of another directory, that is, cookies are path-oriented. As a matter of fact
Even if no path is specified, the WEB server automatically passes the current path to the browser, and the specified path forces the server to use the path of the setting.
The solution to this problem is to add the path and domain name when calling Setcookie, and the format of the domain name can be "www.phpuser.com" or
Is ". Phpuser.com".

The part of the Setcookie function that represents value is automatically encode when passed, that is, if value is "test
Value "becomes" Test%20value "when it is passed, just like the URL method. Of course, this is transparent to the program because
PHP automatically decode the value of the cookie when it receives it.

If you want to set multiple cookies with the same name, use an array by using the following method:

Setcookie ("cookiearray[]", "Value 1");
Setcookie ("cookiearray[]", "Value 2");

Or

Setcookie ("cookiearray[0]", "Value 1");
Setcookie ("cookiearray[1]", "Value 2");

2. Receive and process cookies

PHP's support for cookies receiving and processing is very good, and is completely automatic, as is the principle of form variables, particularly simple. such as setting
Placing a cookie,php named Mycookier will automatically parse it from the HTTP header received by the Web server and form a common
Variable, named $mycookie, the value of this variable is the value of the cookie. Arrays are also applicable. Another option is to refer to PHP
$http_cookie_vars array of global variables.

Examples are as follows: (assuming that these are set in the previous page and still valid)

Echo $MyCookie;
echo $CookieArray [0];
echo count ($CookieArray);
echo $HTTP _cookie_vars["MyCookie"];

It's as simple as that.

3, delete cookies

There are two ways to delete a cookie that already exists:

One is to invoke a Setcookie with only the name parameter, and the cookie named this name will be deleted from the connections machine;
The method is to set the expiration time for the cookie () or ()-1, so that the cookie is deleted after the page has been browsed (its
is actually ineffective).

Note that when a cookie is deleted, its value is still valid on the current page.

4, the use of cookies limit

First, it must be set before the content output of the HTML file;
Second, different browsers are inconsistent with cookie processing, and sometimes the results of the error occur. For example: MS ie+service PACK 1
Cannot properly handle cookies with domain names and paths, Netscape Communicator 4.05 and Ms IE 3.0 do not correctly handle without paths and
Cookie for the time. As for Ms IE 5, it seems unable to handle cookies with domain names, paths, and time. This is the page I designed this site to find
Of
The third limit is on the client. The maximum number of cookies a browser can create is 30, and each cannot exceed 4KB per Web
The total number of cookies a site can set cannot exceed 20.

This is the topic of cookies.

(Since the cookie was originally defined by Netscape, it is accompanied by the official website of Netscape about the original definition of cookies:
_spec.html "Target=_blank>http://www.netscape.com/newsref
/std/cookie_spec.html)

Cookie technology is a very controversial technology, since its inception it has become a vast number of network users and web developers
A point of contention. Some Internet users, even some senior web experts, are dissatisfied with its generation and promotion, not because
Cookie technology is too weak or other technical performance reasons, but simply because they feel the use of cookies, the privacy of network users
Poses a hazard. Because cookies are small text files saved by the Web server in the user's browser, they contain information about the user, such as identity
Identify the number, password, how users are shopping on the Web site, or how many times the user has visited the site.

So what about cookie technology? Whether it really brings personal privacy to the network users of the harm. Or let's look at the bottom of the
Let's do the answer again.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.