同一VPS下多网站无法共享PHP $_SESSION变量的排查咨询
Hey Matancy, no worries about your English at all—let’s work through this step by step! Even if you’ve confirmed the session storage path matches, there are several key settings to check when trying to share $_SESSION variables between two sites:
Verify the session cookie domain
Thesession.cookie_domainsetting needs to be a parent domain that covers both of your sites. For example, if your sites aresite1.yourdomain.frandsite2.yourdomain.fr, set this to.yourdomain.fr(don’t forget the leading dot!). You can check the current value withecho ini_get('session.cookie_domain');on both sites, or set it explicitly usingsession_set_cookie_params()before starting the session.Ensure identical session names
If one site has modified thesession.nameconfiguration (defaults toPHPSESSID), the two sites will use different session identifiers and won’t recognize each other’s sessions. Runecho session_name();on both sites to confirm they return the exact same value.Check the session cookie path
Setsession.cookie_pathto/so the session cookie is accessible across all paths of your domain. If one site has this set to a specific subpath (like/site1/), the other site won’t receive the cookie. Verify this withecho ini_get('session.cookie_path');.Confirm session directory permissions and PHP user
Even if the storage path is the same, make sure the PHP process running both sites has read/write access to the session directory. Check if both sites use the same PHP runtime user (e.g.,www-datafor Apache/Nginx) withps aux | grep php-fpm(if using PHP-FPM), and verify the directory permissions withls -ld /your/session/storage/path.Match session serialization handlers
If thesession.serialize_handlersetting differs between sites (e.g., one usesphpand the otherphp_serialize), the session data will be stored in incompatible formats. Check this withecho ini_get('session.serialize_handler');and ensure both sites use the same handler.Check session strict mode
Ifsession.use_strict_modeis enabled (set to1), PHP will reject unrecognized session IDs and generate new ones. This can break sharing if there’s a mismatch in session ID generation. Try temporarily setting this to0to test if it resolves the issue.Validate cookie security settings
- If
session.cookie_secureis1, the session cookie will only be sent over HTTPS. If one of your sites uses HTTP, it won’t receive the cookie. Ensure both sites use the same protocol or adjust this setting accordingly. - While
session.cookie_httponly(prevents JS access to cookies) doesn’t affect PHP-to-PHP session sharing, make sure this setting is consistent between sites to avoid unexpected behavior.
- If
内容的提问来源于stack exchange,提问作者Matancy

