简体   繁体   中英

example.com and www.example.com are treated as different sessions

So i have a small website that requires users to log in with a username and password. Everything works fine apart from 1 tiny problem

when the user logs in using the url studeez.net , he or she is redirected to a page where the top bar displays his Firstname, lastname and an option to logout.

But if i add www. before the link so that it becomes www.studeez.net , the user is given the login /register options.

This is quite the issue because when the user tries to log in, he or she gets a feedback that they are already logged in.

How do i harmonize studeez.net and www.studeez.net as well as all the subsequent urls like studeez.ney/path/to/page and www.studeez.ney/path/to/page

You need to force the www or no-www to keep user session on the same site. You can use this htaccess condition to rewrite to the correct domain. This example will force the use of www .

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^yoursite.com [NC]
RewriteRule ^(.*)$ http://www.yoursite.com/$1 [R=301,NC,L]
</IfModule>

Possible duplicate of this question .

Baring using .htaccess files or modifying the server configuration to use mod_rewrite, this should work fine as a pure PHP solution:

$sname = session_name(); // Get the name of the session cookie.
if ( !isset($_SESSION) ) session_start(); // If a session has not been started then start one.
$sid = ( isset($_COOKIE[$sname]) ) ? session_id($_COOKIE[$sname]) : session_id();  // Get an encrypted session identifier.
setcookie($sname, $sid, time()+86400, "/", ".example.com", false, true); // Set the .example.com cookie so we can work across all sub-domains.

Change the .example.com to whatever your domain name is in the . domain.tld format without a sub-domain, but including the period at the beginning. This should set a cookie which works across all sub-domains of your domain.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM