PHP中cookies指南_PHP
Cookie
综述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能转换可识别的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重写的要求。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



With the rapid development of social media, Xiaohongshu has become one of the most popular social platforms. Users can create a Xiaohongshu account to show their personal identity and communicate and interact with other users. If you need to find a user’s Xiaohongshu number, you can follow these simple steps. 1. How to use Xiaohongshu account to find users? 1. Open the Xiaohongshu APP, click the "Discover" button in the lower right corner, and then select the "Notes" option. 2. In the note list, find the note posted by the user you want to find. Click to enter the note details page. 3. On the note details page, click the "Follow" button below the user's avatar to enter the user's personal homepage. 4. In the upper right corner of the user's personal homepage, click the three-dot button and select "Personal Information"

In Ubuntu systems, the root user is usually disabled. To activate the root user, you can use the passwd command to set a password and then use the su- command to log in as root. The root user is a user with unrestricted system administrative rights. He has permissions to access and modify files, user management, software installation and removal, and system configuration changes. There are obvious differences between the root user and ordinary users. The root user has the highest authority and broader control rights in the system. The root user can execute important system commands and edit system files, which ordinary users cannot do. In this guide, I'll explore the Ubuntu root user, how to log in as root, and how it differs from a normal user. Notice

With the launch of Windows 11, Microsoft has introduced some new features and updates, including a security feature called VBS (Virtualization-basedSecurity). VBS utilizes virtualization technology to protect the operating system and sensitive data, thereby improving system security. However, for some users, VBS is not a necessary feature and may even affect system performance. Therefore, this article will introduce how to turn off VBS in Windows 11 to help

VSCode Setup in Chinese: A Complete Guide In software development, Visual Studio Code (VSCode for short) is a commonly used integrated development environment. For developers who use Chinese, setting VSCode to the Chinese interface can improve work efficiency. This article will provide you with a complete guide, detailing how to set VSCode to a Chinese interface and providing specific code examples. Step 1: Download and install the language pack. After opening VSCode, click on the left

sudo (superuser execution) is a key command in Linux and Unix systems that allows ordinary users to run specific commands with root privileges. The function of sudo is mainly reflected in the following aspects: Providing permission control: sudo achieves strict control over system resources and sensitive operations by authorizing users to temporarily obtain superuser permissions. Ordinary users can only obtain temporary privileges through sudo when needed, and do not need to log in as superuser all the time. Improved security: By using sudo, you can avoid using the root account during routine operations. Using the root account for all operations may lead to unexpected system damage, as any mistaken or careless operation will have full permissions. and

Detailed explanation of jQuery reference method: Quick start guide jQuery is a popular JavaScript library that is widely used in website development. It simplifies JavaScript programming and provides developers with rich functions and features. This article will introduce jQuery's reference method in detail and provide specific code examples to help readers get started quickly. Introducing jQuery First, we need to introduce the jQuery library into the HTML file. It can be introduced through a CDN link or downloaded

With the continuous development of technology, Linux operating systems have been widely used in various fields. Installing Deepin Linux system on tablets allows us to experience the charm of Linux more conveniently. Let’s discuss the installation of Deepin Linux on tablets. Specific steps for Linux. Preparation work Before installing Deepin Linux on the tablet, we need to make some preparations. We need to back up important data in the tablet to avoid data loss during the installation process. We need to download the image file of Deepin Linux and write it to to a USB flash drive or SD card for use during the installation process. Next, we can start the installation process. We need to set the tablet to start from the U disk or SD

Analysis of user password storage mechanism in Linux system In Linux system, the storage of user password is one of the very important security mechanisms. This article will analyze the storage mechanism of user passwords in Linux systems, including the encrypted storage of passwords, the password verification process, and how to securely manage user passwords. At the same time, specific code examples will be used to demonstrate the actual operation process of password storage. 1. Encrypted storage of passwords In Linux systems, user passwords are not stored in the system in plain text, but are encrypted and stored. L
