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

PHP中cookies使用指南

Jun 13, 2016 pm 12:33 PM
cookie cookies http php Down user's guidance protocol Can client server maintain Overview Script

综述 
  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)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles