Yii2 realizes multi-domain cross-domain synchronous login and exit

高洛峰
Release: 2023-03-05 13:24:01
Original
1396 people have browsed it

During the platform development process, the project is divided into two parts: frontend (frontend) www.xxx.com and backend (backend) yun.xxx.com. Two domain names are bound. We know that when the domain name is not bound, the frontend The background can log in and log out synchronously, but it will become invalid after binding the domain name. The reason is that the scope of the session is different. The session scope of the two domain names is only limited to their own domain names. Our solution is to change the scopes of different second-level domain names to the top-level domain name xxx.com.

Add the following code in common/config/main.PHP:

//跨域session域名配置,获取当前主机名 
$host_array = explode('.', $_SERVER["HTTP_HOST"]); 
//针对com域名,获取顶级域名 
if (count($host_array) == 3) { 
  define('DOMAIN', $host_array[1] . '.' . $host_array[2]); 
} 
//针对com.cn域名 
elseif (count($host_array) == 4) { 
  define('DOMAIN', $host_array[1] . '.' . $host_array[2]. '.' . $host_array[3]); 
} 
else{ 
  //echo "本系统不支持本地访问,请配置域名";exit; 
} 
define('DOMAIN_HOME', 'www.' . DOMAIN); 
define('DOMAIN_YUN', 'yun.' . DOMAIN); 
define('DOMAIN_API', 'api.' . DOMAIN); 
define('DOMAIN_EMAIL', 'mail.' . DOMAIN); 
define('DOMAIN_IMG', 'img.' . DOMAIN);
Copy after login

Modify the components part and change the session scope

'user' => [ 
      'identityClass' => 'common\models\User', 
      'enableAutoLogin' => true, 
      'identityCookie' => ['name' => '_identity', 'httpOnly' => true, 'domain' => '.' . DOMAIN], 
    ], 
    'session' => [ 
      'cookieParams' => ['domain' => '.' . DOMAIN, 'lifetime' => 0], 
      'timeout' => 3600, 
    ],
Copy after login

After passing the above configuration, more Synchronous login and logout can be achieved between two second-level domain names.

The above is the entire content of this article. I hope it will be helpful to everyone's study. I also hope that everyone will support the PHP Chinese website.

For more articles related to Yii2’s implementation of multi-domain cross-domain synchronization login and logout, please pay attention to the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!