Php 简明教程
PHP - Cookies
万维网由 HTTP 协议驱动,该协议是一种无状态协议。Cookie 机制帮助服务器维护以前请求的信息。PHP 透明支持 HTTP cookie。
The worldwide web is powered by HTTP protocol, which is a stateless protocol. The mechanism of Cookies helps the server maintain the information of previous requests. PHP transparently supports HTTP cookies.
-
When a client first sends its request, the server includes a small piece of data along with its response as cookies. PHP provides the setcookie() method to inject cookies in the response.
-
This cookie data is stored in the client’s machine as text files. On subsequent visits of the same client, these cookies are included as a part of the request header.
-
The server populates the PHP superglobal variable "$_COOKIE" with all the cookies present in the client request.
本章将教您如何设置 cookie、如何访问 cookie 以及如何删除 cookie。
This chapter will teach you how to set cookies, how to access them and how to delete them.
The Anatomy of a Cookie
Cookie 通常设置在 HTTP 头中(尽管 JavaScript 也可以直接在浏览器上设置 cookie)。设置 cookie 的 PHP 脚本可能会发送类似以下内容的头:
Cookies are usually set in an HTTP header (although JavaScript can also set a cookie directly on a browser). A PHP script that sets a cookie might send headers that look something like this −
HTTP/1.1 200 OK
Date: Fri, 04 Feb 2000 21:03:38 GMT
Server: Apache/1.3.9 (UNIX) PHP/4.0b3
Set-Cookie: name=xyz; expires=Friday, 04-Feb-07 22:03:38 GMT;
path=/; domain=tutorialspoint.com
Connection: close
Content-Type: text/html
如您所见,Set-Cookie 标头包含一个名称值对、一个 GMT 日期、一个路径和一个域名。名称和值将经过 URL 编码。expires 字段是指示浏览器在给定时间和日期后“忘记”Cookie 的指令。
As you can see, the Set-Cookie header contains a name value pair, a GMT date, a path and a domain. The name and value will be URL encoded. The expires field is an instruction to the browser to "forget" the cookie after the given time and date.
如果浏览器配置为存储 cookie,它会将此信息保留至到期日期。如果用户将浏览器指向与 cookie 路径和域名匹配的任何页面,它将重新发送 cookie 至服务器浏览器头可能类似以下内容:
If the browser is configured to store cookies, it will then keep this information until the expiry 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/4.6 (X11; I; Linux 2.2.6-15apmac ppc)
Host: zink.demon.co.uk:1126
Accept: image/gif, */*
Accept-Encoding: gzip
Accept-Language: en
Accept-Charset: iso-8859-1,*,utf-8
Cookie: name=xyz
随后,PHP 脚本可以访问环境变量 $_COOKIE 或 $HTTP_COOKIE_VARS[]中的 cookie,其中包含所有 cookie 名称和值。可以使用 $HTTP_COOKIE_VARS["name"] 访问上述 cookie。
A PHP script will then have access to the cookie in the environmental variables $_COOKIE or $HTTP_COOKIE_VARS[] which holds all cookie names and values. Above cookie can be accessed using $HTTP_COOKIE_VARS["name"].
How to Set a Cookie in PHP?
PHP 包含 setcookie 函数,用于创建要随 HTTP 响应一起发送给客户端的 cookie 对象。
PHP contains the setcookie function to create a cookie object to be sent to the client along with HTTP response.
setcookie(name, value, expire, path, domain, security);
Parameters
以下是所有参数的详细信息-
Here is the detail of all the arguments −
-
Name − This sets the name of the cookie and is stored in an environment variable called HTTP_COOKIE_VARS. This variable is used while accessing cookies.
-
Value − This sets the value of the named variable and is the content that you actually want to store.
-
Expiry − This specify a future time in seconds since 00:00:00 GMT on 1st Jan 1970. After this time cookie will become inaccessible. If this parameter is not set then cookie will automatically expire when the Web Browser is closed.
-
Path − This specifies the directories for which the cookie is valid. A single forward slash character permits the cookie to be valid for all directories.
-
Domain − This can be used to specify the domain name in very large domains and must contain at least two periods to be valid. All cookies are only valid for the host and domain which created them.
-
Security − This can be set to 1 to specify that the cookie should only be sent by secure transmission using HTTPS otherwise set to 0 which mean cookie can be sent by regular HTTP.
Example
下面给出的 PHP 脚本会检查 Cookie 名称为 username 已经设置,如果已被设置,则会取回其值。如果未设置,则会设置一个新的 Cookie username 。
The PHP script give below checks if the cookie named username is already set, and retrieves its value, if so. If not, a new cookie username is set.
<?php
if (isset($_COOKIE['username'])) {
echo "<h2>Cookie username already set:" . $_COOKIE['username'] . "</h2>";
} else {
setcookie("username", "MohanKumar");
echo "<h2>Cookie username is now set</h2>";
}
?>
从 Apache 服务器的文档根文件夹运行此脚本。您应会看到此消息 −
Run this script from the document root of the Apache server. You should see this message −
Cookie username is now set
如果重新执行此脚本,则现在已设置 Cookie。
If this script is re-executed, the cookie is now already set.
Cookie username already set: MohanKumar
浏览器的开发者工具是非常有用的工具。您可通过该工具设置、取回、删除 Cookie。由上述程序设置的 Cookie 可在浏览器的开发者工具的“应用程序”选项卡下查看。
Your browser’s developer tool is a very useful facility. You can set, retrieve and delete cookies with its help. The cookie set by the above program can be viewed under the Application tab of the browser’s developer tools.
如下面的 foreach 循环会取回所有 Cookie −
A foreach loop as below retrieves all the cookies −
<?php
$arr=$_COOKIE;
foreach ($arr as $key=>$val);
echo "<h2>$key=>$val </h2>";
?>
以下脚本包含一个 HTML 表单。它会将表单数据发送至 setcookie.php 脚本,该脚本会使用从 $_POST 数组取回的数据设置 Cookie。
The following script contains an HTML form. It sends the form data to setcookie.php script, that sets the cookies with the use of data retrieved from the $_POST array.
以下代码会呈现 HTML 表单 −
The HTML form is rendered by the following code −
<form action="setcookie.php" method="POST">
<input type="text" name="name">
<input type="text" name="age">
<input type="submit" name="Submit">
</form>
SetCookie.php 会读取表单数据并设置 Cookie。
SetCookie.php reads the form data and sets the cookies.
if (isset($_POST["submit"]) {
setcookie("name", $_POST["name"]);
setcookie("age", $_POST["age"]);
}
我们可通过另一个 getcookie.php 代码取回所设置的 Cookie。
With another getcookie.php code, we can retrieve the cookies set.
if (isset($_COOKIE["name"])
echo "Cookie: name => " . $_COOKIE["name"]. "<br>";
if (isset($_COOKIE["age"])
echo "Cookie: age => " . $_COOKIE["age"]. "<br>";
Accessing Cookies with PHP
PHP 提供了许多访问 Cookie 的方法。最简单的方法是使用 $_COOKIE 或 $HTTP_COOKIE_VARS 变量。以下示例将访问上述示例中设置的所有 Cookie。
PHP provides many ways to access cookies. Simplest way is to use either $_COOKIE or $HTTP_COOKIE_VARS variables. Following example will access all the cookies set in above example.
<?php
echo $_COOKIE["name"]. "<br />";
/* is equivalent to */
echo $HTTP_COOKIE_VARS["name"]. "<br />";
echo $_COOKIE["age"] . "<br />";
/* is equivalent to */
echo $HTTP_COOKIE_VARS["age"] . "<br />";
?>
您可以使用 isset() 函数检查 Cookie 是否已经设置。
You can use isset() function to check if a cookie is set or not.
<?php
if( isset($_COOKIE["name"]))
echo "Welcome " . $_COOKIE["name"] . "<br />";
else
echo "Sorry... Not recognized" . "<br />";
?>
Deleting the Cookies
要删除 Cookie,请使用在浏览器已经过期的日期设置 Cookie,以便浏览器触发 Cookie 删除机制。
To delete cookie set the cookie with a date that has already expired, so that the browser triggers cookie removal mechanism.
Example
请看以下示例:
Take a look at the following example −
<?php
setcookie("username", "", time() - 3600);
echo "<h2>Cookie username is now removed</h2>";
?>
浏览器会显示以下响应 −
The browser shows the following response −
Cookie username is now removed
您还可以通过在 Cookie 名称中使用数组符号来设置数组 Cookie。
You may also set array cookies by using array notation in the cookie name.
setcookie("user[three]", "Guest");
setcookie("user[two]", "user");
setcookie("user[one]", "admin");
如果 Cookie 名称包含句点 (.),则 PHP 会将它们替换为下划线 (_)。
If the cookie name contains dots (.), PHP replaces them with underscores (_).
虽然 Cookie 概念的主要目的是帮助 Web 开发者提供更为个性化、更为便捷的用户体验,但它可能会对您的隐私和个人信息构成风险。
Although the main purpose behind the concept of cookies is to help web developers provide a more personalized and convenient user experience, it may pose a risk to your privacy and personal information.
在某些情况下,如果你不接受应用的 cookies,应用可能会拒绝你完全访问。在这种情况下,建议定期清理浏览器缓存中的 cookie 相关数据。
In some cases, the application may deny you full access you don’t accept their cookies. In such cases, periodically clearing the cookie related data from your browser’s cache is advised.