本文实例讲述了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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
< 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
在最后添加
1
|
127.0.0.1 www.koastal.com login.koastal.com |
编写php代码进行测试
D:\wamp64\vhosts\www\index.php
1
2
3
4
5
6
7
8
9
|
<?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
1
2
3
4
5
6
7
8
9
10
11
|
<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程序设计有所帮助。
原文链接:https://blog.csdn.net/koastal/article/details/70146759