Home > Backend Development > PHP Tutorial > How to Share PHP Sessions Across Subdomains?

How to Share PHP Sessions Across Subdomains?

Linda Hamilton
Release: 2024-12-13 13:49:13
Original
477 people have browsed it

How to Share PHP Sessions Across Subdomains?

Cross-Subdomain Session Sharing in PHP

When managing user sessions across multiple subdomains, ensuring seamless login and data persistence is crucial. In this scenario, you need to allow subdomains to access the authorized sessions created on the primary domain.

You have tried setting the session.cookie_domain in your php.ini to .example.com to enable cross-subdomain cookie sharing. However, your code doesn't appear to be reading the shared session data.

To resolve this, try the following:

// sub1.example.com  
session_name('YOUR_SESSION_NAME'); // Add a unique name, e.g., 'my_session'
session_set_cookie_params(0, '/', '.example.com');
session_start();
print session_id() . "<br>";
$_SESSION['Registered'] = 1;
echo '<a href="http://auth.example.com/test.php">Change Sites</a>';

// auth.example.com
session_name('YOUR_SESSION_NAME'); // Match the name from sub1.example.com
session_set_cookie_params(0, '/', '.example.com');
session_start();
print session_id() . "<br>";
$_SESSION['Checked'] = 1;
print_r($_SESSION);
Copy after login

By adding session_name('YOUR_SESSION_NAME'); before setting the cookie parameters, you ensure that the subdomains use the same session name. This allows them to access and modify the shared session data. Replace YOUR_SESSION_NAME with a unique identifier.

The above is the detailed content of How to Share PHP Sessions Across Subdomains?. For more information, please follow other related articles on the PHP Chinese website!

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template