本文实例讲述了PHP Apache实现二级域名之间共享cookie的方法。分享给大家供大家参考,具体如下:
简介
login.koastal.com设置domain为koastal.com,则www.koastal.com即可访问该cookie。 也就是说二级域名(或者三级域名)之间可以通过这种方式共享cookie。 其实cookie的domain属性的用法跟path有些类似,比如我们将cookie的path设置为/,则/user目录下也可以访问该cookie。
实践
Apache同一端口对应不同域名
httpd-vhosts.conf
代码语言:javascript复制<VirtualHost 127.0.0.1:80
ServerName koastal.com
ServerAlias www.koastal.com
DocumentRoot D:wamp64vhostswww
<Directory "D:wamp64vhostswww"
Options Indexes Includes FollowSymLinks MultiViews
AllowOverride All
Require local
</Directory
</VirtualHost
<VirtualHost 127.0.0.1:80
ServerName login.koastal.com
DocumentRoot D:wamp64vhostslogin
<Directory "D:wamp64vhostslogin"
Options Indexes Includes FollowSymLinks MultiViews
AllowOverride All
Require local
</Directory
</VirtualHost
修改本机hosts
windows
C:WINDOWS/system32/drivers/etc/hosts
linux
vim /etc/hosts
在最后添加
代码语言:javascript复制127.0.0.1 www.koastal.com login.koastal.com
编写php代码进行测试
D:wamp64vhostswwwindex.php
代码语言:javascript复制<?php
if(isset($_COOKIE['username'])){
echo "welcome to ".$_COOKIE['username'];
var_dump($_COOKIE);
}else{
?
<h1 <a href='http://login.koastal.com' Login</a </h1
<?php
}
D:wamp64vhostsloginindex.php
代码语言:javascript复制<form action="#" method="post"
<p username:<input type="text" name="username" </p
<p password:<input type="password" name="password" </p
<p <input type="submit" name="submit" value="submit" </p
</form
<?php
if(isset($_POST['submit'])){
setcookie('username',$_POST['username'],0,'/','koastal.com');
setcookie('password',$_POST['password'],0,'/','koastal.com');
header('Location:http://www.koastal.com');
}
亲测可用,全文完~