本文实例讲述了PHP+Apache实现二级域名之间共享cookie的方法。分享给大家供大家参考,具体
本文实例讲述了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
<VirtualHost 127.0.0.1:80>
ServerName koastal.com
ServerAlias www.koastal.com
DocumentRoot D:\wamp64\vhosts\www
<Directory "D:\wamp64\vhosts\www">
Options +Indexes +Includes +FollowSymLinks +MultiViews
AllowOverride All
Require local
</Directory>
</VirtualHost>
<VirtualHost 127.0.0.1:80>
ServerName login.koastal.com
DocumentRoot D:\wamp64\vhosts\login
<Directory "D:\wamp64\vhosts\login">
Options +Indexes +Includes +FollowSymLinks +MultiViews
AllowOverride All
Require local
</Directory>
</VirtualHost>
修改本机hosts
windows
C:WINDOWS/system32/drivers/etc/hosts
linux
vim /etc/hosts
在最后添加
127.0.0.1 www.koastal.com login.koastal.com
编写php代码进行测试
D:\wamp64\vhosts\www\index.php
<?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:\wamp64\vhosts\login\index.php
<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');
}
亲测可用,全文完~
PHP Apache 二级域名 共享cookie