Heim >Backend-Entwicklung >PHP-Tutorial >PHP中cookies指南_PHP
Cookie
综述init setcookie(string CookieName,string CookieValue,int CookieExpireTime,path,domain,int secure);
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)
<? if (isset($myCookies)) { // 如果Cookie已经存在
……
} else { //如果Cookie不存在
……
}
?>
$info = explode("&", $myCookies);
……
$count ;
$CookieString=$FirstName.'&'.$LastName.'&'.$email.'&'.$count;
SetCookie ("myCookies",$CookieString, time() 3600); //设置cookie
/* 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>
/* 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"];
$count ; //增加计数器
$CookieString=$FirstName.'&'.$LastName.'&'.$email.'&'.$count;
SetCookie ("myCookies",$CookieString, time() 3600);
<?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.
<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>