Home php教程 php手册 PHP中cookies指南

PHP中cookies指南

Jun 21, 2016 am 09:14 AM
cookie http quot

cookie|cookies

综述

Cookie是在HTTP协议下,服务器或脚本可以维护客户工作站上信息的一种方式。Cookie是由Web服务器保存在用户浏览器上的小文件,它可以包含有关用户的信息(如身份识别号码、密码、用户在Web站点购物的方式或用户访问该站点的次数)。无论何时用户链接到服务器,Web站点都可以访问Cookie信息。

  怎样设置cookies?

在PHP中可以使用setcookie函数设置一个cookie。cookie是 HTTP标头的一部分, 因此设置cookie功能必须在任何内容送到浏览器之前。这种限制与header()函数一样。任何从客户端传来的cookie将自动地转化成一个PHP变量。PHP取得信息头并分析, 提取cookie名并变成变量。因此,如果设置cookie如setcookie("mycookie","Cookies")php将自动产生一个名为$mycookie,值为"Cookies"的变量。

我们来看一下setcookie函数语法:

init setcookie(string CookieName,string CookieValue,int CookieExpireTime,path,domain,int secure);

参数说明:

PATH:表示web服务器上的目录,默认为被调用页面所在目录

DOMAIN:cookie可以使用的域名,默认为被调用页面的域名。这个域名必须包含两个".",所以如果你指定你的顶级域名,你必须用".mydomain.com"

SECURE:如果设为"1",表示cookie只能被用户的浏览器认为是安全的服务器所记住.

cookies使用举例

假设我们有这样一个需要注册的站点,它自动识别用户的身份并进行相关的操作:如果是已经注册的用户,发送给他信息;如果不是已经注册的用户,则显示一个注册页面的链接。

按照上面的要求,我们先创建数据库用来保存注册用户的信息:名字(first name),姓(last name),Email地址(email address),计数器(visit counter)。

先按下面步骤建表:

mysql> create database users;
Query OK, 1 row affected (0.06 sec)
mysql> use users;
Database changed
mysql> create table info (FirstName varchar(20), LastName varchar(40), email varchar(40), count varchar(3));
Query OK, 0 rows affected (0.05 sec)



然后建一个php页面对照数据库检查cookies。

由于php能转换可识别的cookie为相应的变量,所以我们能检查一个名为"myCookies" 的变量:

<? if (isset($myCookies)) { // 如果Cookie已经存在
……
} else { //如果Cookie不存在
……
}
?>

当cookie存在时,我们执行下面步骤:

首先取得cookie值,用explode函数分析成不同的变量,增加计数器,并设一个新cookie:

$info = explode("&", $myCookies);
……
$count++;
$CookieString=$FirstName.'&'.$LastName.'&'.$email.'&'.$count;
SetCookie ("myCookies",$CookieString, time()+3600); //设置cookie

接着用html语句输出用户信息。

最后,用新的计数器值更新数据库。

如果这个cookie不存在,我们显示一个注册页(register.php)的链接。

下面的register.php是用户注册页面:

/* register.php */
<form method="post" action="regOK.php">
First Name:<input type="text" name="FirstName">
Last Name:<input type="text" name="LastName">
<input type="submit" value="注册">
</form>

用户在register.php注册页面填写的信息提交给regOK.php:

/* regOK.php */
if ($FirstName and $LastName and $email) {
 ……//在数据库查询用户是否存在
}
}else{
……//错误处理
}




上面的程序流程如下:

首先检查所有的信息是否按要求填写,如果没有,返回重新输入

如果所有信息填好,首先,我们从数据库中取回用户登录详细资料

mysql_connect() or die ("连接数据库出现错误!");
$query="select * from info where FirstName='$FirstName' and LastName='$LastName' and email='$email'";
$result = mysql_db_query("users", $query);
$info=mysql_fetch_array($result);
$count=$info["count"];

检查数据库是否有这样一个用户,如果有,它指定旧的信息,并用当前的信息建一新的cookie,如果同一用户没有数据库登录,新建一数据库登录,并建一新的cookie。

现在利用isset()函数检查用户是否有计数器,如果有则计数器增加并且建立一个新的cookie:

$count++; //增加计数器
$CookieString=$FirstName.'&'.$LastName.'&'.$email.'&'.$count;
SetCookie ("myCookies",$CookieString, time()+3600);

如果没有一用户计数器,在mysql中加一记录,并设一cookie

注意:调用setcookie函数之前应该没有任何数据输出倒浏览器,否则将会出现错误。

  如何实现跨域名Cookie?

  从Cookie规范上说,一个cookie只能用于一个域名,因此,如果在浏览器中对一个域名设置了一个cookie,那么这个cookie对于其它的域名将无效。

  下面我们来谈一个跨域名cookie的实现方案:

第一步:创建预置脚本

  将下面的代码加到预置脚本中(或出现在所有脚本之前的函数中)。

    <?php
    /*如果GET变量已经设置了,并且它与cookie变量不同
     *则使用get变量(更新cookie)
     */
    global $HTTP_COOKIE_VARS, $HTTP_GET_VARS;
    if (isset($sessionid) && isset($HTTP_GET_VARS['sessionid']) && ($HTTP_COOKIE_VARS['sessionid'] != $HTTP_GET_VARS['sessionid'])) {
      SetCookie('sessionid', $HTTP_GET_VARS['sessionid'], 0, '/', '');
      $HTTP_COOKIE_VARS['sessionid'] = $HTTP_GET_VARS['sessionid'];
      $sessionid = $HTTP_GET_VARS['sessionid'];
    }
    ?>

这个代码运行之后,一个全局变量'sessionid'将可以用于脚本。它将保存用户的cookie中的sessionid值,或者是通过GET请求发来的sessionid值。

第二步:为所有的交叉域名引用使用变量

  创建一个全局的配置文件,用于存放可以进行切换的域名的基本引用形式。例如,如果我们拥有domain1.com和domain2.com,则如下设置:

    <?php
    $domains['domain1'] = "http://www.domain1.com/-$sessionid-";
    $domains['domain2'] = "http://www.domain2.com/-$sessionid-";
    ?>

  我们写这样一段代码:

    <?php
    echo "Click <a href="", $domains['domain2'], "/contact/?email=yes">here</a> to contact us.";
    ?>

  上面的代码将产生如下的输出:

    Click <a href="http://www.domain2.com/-66543afe6543asdf6asd-/contact/?email=yes">here</a> to contact us.

  在这里sessionid已经被插入到URL中去了。

第三步:配置Apache

  现在,我们来配置Apache来重写这个URL。

  我们需要将
    http://www.domain2.com/-66543afe6543asdf6asd-/contact/
  变成这样:
    http://www.domain2.com/contact/?sessionid=66543afe6543asdf6asd
  并且这种url:
    http://www.domain2.com/-66543afe6543asdf6asd-/contact/?email=yes
  变成这样:
    http://www.domain2.com/contact/?email=yes&sessionid=66543afe6543asdf6asd

  为了实现上面的要求,简单地配置两个虚拟服务器,作为domain1和domain2,如下操作:

    <VirtualHost ipaddress>
    DocumentRoot /usr/local/www/domain1
    ServerName www.domain1.com
    RewriteEngine on
    RewriteRule ^/-(.*)-(.*?.*)$ $2&sessionid=$1 [L,R,QSA]
    RewriteRule ^/-(.*)-(.*)$ $2?sessionid=$1 [L,R,QSA]
    </VirtualHost>

    <VirtualHost ipaddress>
    DocumentRoot /usr/local/www/domain2
    ServerName www.domain2.com
    RewriteEngine on
    RewriteRule ^/-(.*)-(.*?.*)$ $2&sessionid=$1 [L,R,QSA]
    RewriteRule ^/-(.*)-(.*)$ $2?sessionid=$1 [L,R,QSA]
    </VirtualHost>

  这些重写的规则实现了上面两个URL重写的要求。



Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Where are cookies stored? Where are cookies stored? Dec 20, 2023 pm 03:07 PM

Cookies are usually stored in the cookie folder of the browser. Cookie files in the browser are usually stored in binary or SQLite format. If you open the cookie file directly, you may see some garbled or unreadable content, so it is best to use Use the cookie management interface provided by your browser to view and manage cookies.

Where are the cookies on your computer? Where are the cookies on your computer? Dec 22, 2023 pm 03:46 PM

Cookies on your computer are stored in specific locations on your browser, depending on the browser and operating system used: 1. Google Chrome, stored in C:\Users\YourUsername\AppData\Local\Google\Chrome\User Data\Default \Cookies etc.

Understand common application scenarios of web page redirection and understand the HTTP 301 status code Understand common application scenarios of web page redirection and understand the HTTP 301 status code Feb 18, 2024 pm 08:41 PM

Understand the meaning of HTTP 301 status code: common application scenarios of web page redirection. With the rapid development of the Internet, people's requirements for web page interaction are becoming higher and higher. In the field of web design, web page redirection is a common and important technology, implemented through the HTTP 301 status code. This article will explore the meaning of HTTP 301 status code and common application scenarios in web page redirection. HTTP301 status code refers to permanent redirect (PermanentRedirect). When the server receives the client's

Where are the mobile cookies? Where are the mobile cookies? Dec 22, 2023 pm 03:40 PM

Cookies on the mobile phone are stored in the browser application of the mobile device: 1. On iOS devices, Cookies are stored in Settings -> Safari -> Advanced -> Website Data of the Safari browser; 2. On Android devices, Cookies Stored in Settings -> Site settings -> Cookies of Chrome browser, etc.

HTTP 200 OK: Understand the meaning and purpose of a successful response HTTP 200 OK: Understand the meaning and purpose of a successful response Dec 26, 2023 am 10:25 AM

HTTP Status Code 200: Explore the Meaning and Purpose of Successful Responses HTTP status codes are numeric codes used to indicate the status of a server's response. Among them, status code 200 indicates that the request has been successfully processed by the server. This article will explore the specific meaning and use of HTTP status code 200. First, let us understand the classification of HTTP status codes. Status codes are divided into five categories, namely 1xx, 2xx, 3xx, 4xx and 5xx. Among them, 2xx indicates a successful response. And 200 is the most common status code in 2xx

Detailed explanation of where browser cookies are stored Detailed explanation of where browser cookies are stored Jan 19, 2024 am 09:15 AM

With the popularity of the Internet, we use browsers to surf the Internet have become a way of life. In the daily use of browsers, we often encounter situations where we need to enter account passwords, such as online shopping, social networking, emails, etc. This information needs to be recorded by the browser so that it does not need to be entered again the next time you visit. This is when cookies come in handy. What are cookies? Cookie refers to a small data file sent by the server to the user's browser and stored locally. It contains user behavior of some websites.

How to implement HTTP streaming using C++? How to implement HTTP streaming using C++? May 31, 2024 am 11:06 AM

How to implement HTTP streaming in C++? Create an SSL stream socket using Boost.Asio and the asiohttps client library. Connect to the server and send an HTTP request. Receive HTTP response headers and print them. Receives the HTTP response body and prints it.

How to solve the problem that document.cookie cannot be obtained How to solve the problem that document.cookie cannot be obtained Nov 23, 2023 am 10:02 AM

Solutions for document.cookie not being obtained: 1. Browser privacy settings; 2. Same-origin policy; 3. HTTPOnly Cookie; 4. JavaScript code error; 5. Cookie does not exist or expires; 6. Cross-domain issues; 7. Viewer mode; 8. Server problems; 9. JavaScript execution timing; 10. Check console log, etc.

See all articles