PHP+Apache Method for Sharing cookie between Two Domain Names
- 2021-12-13 16:29:06
- OfStack
This paper gives an example of PHP + Apache to share cookie between two level domain names. Share it for your reference, as follows:
Brief introduction
login. koastal. com Set domain to koastal. com, then www. koastal. com can access the cookie.
That is to say, cookie can be shared between level 2 domain names (or level 3 domain names) in this way.
In fact, the usage of domain attribute of cookie is somewhat similar to that of path. For example, if we set path of cookie to/, the cookie can also be accessed in the/user directory.
Practice
Apache and port 1 correspond to different domain names
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>
Modify native hosts
windows
C:WINDOWS/system32/drivers/etc/hosts
linux
vim /etc/hosts
Add at the end
127.0.0.1 www.koastal.com login.koastal.com
Write php code for testing
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');
}
Pro-test available, full text ~
For more readers interested in PHP related content, please check the topics of this site: "Summary of cookie Usage in PHP", "Encyclopedia of PHP Array (Array) Operation Skills", "Introduction to PHP Basic Grammar", "Summary of PHP Operation and Operator Usage", "Summary of PHP Network Programming Skills" and "Summary of php String (string) Usage"
I hope this article is helpful to everyone's PHP programming.