bikey77
bikey77

Reputation: 6672

PHP - Two pages, two sessions, same values

If two websites use the same session variables (they share the same code that I've written) and I have them open in the same browser (in two tabs), the session for SiteA gets mixed up with SiteB's values and vice versa. For example, if I set $_SESSION['var1']=1 in SiteA and then open SiteB in the same browser and perform an array_dump($_SESSION) then I see var1 in the dump.

What can I do to have a set of session variables stay within the "scope" of only one site?

Upvotes: 0

Views: 566

Answers (3)

TRiG
TRiG

Reputation: 10643

If you have two separate sites running on the same domain name, they will indeed share session data by default, but you can change that. The name of the session cookie is set in php.ini as the session.name directive (by default, it's PHPSESSID), but you can overwrite that with session_name().

What you want to do is to call the session cookie on one site SessionSiteA instead (note, the session name must be alphanumeric, and must contain at least one letter).

So your options are (a) have a different php.ini file for each site; (b) overwrite the value in .htaccess (this is allowed for some, but not all, php.ini settings, and I can't currently work out how to do it for session.name: it may not be possible); or (c) call the session_name() function in one of the sites before setting or reading any sessions. Note that session_name() can be computationally expensive, so use it with care (perhaps on one of the sites only, leaving the busier site to use the default PHPSESSID).

Note: Another option might be to save sessions from each site in a different place, using ini_set('session.save_path', ...) differently on each site. As above, this would have to be done centrally, before any sessions are set or used.

Upvotes: 0

lupatus
lupatus

Reputation: 4248

I suppose those sessions are under same domain and both are using same session cookie name. Change names for this sessions using session_name (before you'll run session_start).

https://www.php.net/manual/en/function.session-name.php

Upvotes: 1

Dr.Kameleon
Dr.Kameleon

Reputation: 22820

Maybe add some prefix to your session variables to distinguish one from the other ?

E.g.

siteA_loggedIn
siteB_loggedIn

Upvotes: 0

Related Questions