PHP sessions on subpages of the same domain

I have one domain (domain.com) with several subpages that have different sessions (default), and I want some of these subpages to share the session.

So for example, I have domain.com/section1/staff/ and domain.com/section2/staff/ . I use the $_SESSION variable to store information for the current user, and I want to be able to log in once in section1/staff/ and still log in when I go to section2/staff/ .

From reading other messages, it seems that this is the default method that the session should execute, and the domain is not set on both pages, and the path is // in session_get_cookie_params() , so it should be the same session, but it does not pass the variable $_SESSION , and even when I call session_destroy() , it does not destroy another session.

Is there a way to explicitly set the same for them (or another place to look for default settings that are not displayed in the session_get_cookie_params() array)?

+4
source share
3 answers

The problem was that one section forced the domain.com URL and the other forced it to be bound to www.domain.com.

0
source

By default, PHP will use the same session for all scripts in the same domain. Make sure to bounce between domain.com and www.domain.com as they may not have the same session.

Instead of creating completely separate sessions for each section, why not use one global session for the user and the section? There is no reason that $ _SESSION cannot be a multidimensional array.

 //// things needed in multiple sections could go into a common grouping: $_SESSION['common']['user'] = 'josh'; $_SESSION['common']['privileges']['section_access'] = array( 'section1'=>"yes", 'section2'=>"no", 'section5'=>"security-prompt" ); //// while things that were section specific could be grouped by section: $_SESSION['section1']['agreed_to_terms'] = true; //// you could also group by logical functionality: $_SESSION['staff']['badge_no'] = 44815; 

Using this structure, you will have all the information available to you in each script, but use only the parts that you need.

In addition, it saves you the headache of juggling session_name () and other complex bits in your logic. In addition, this solves the problem of exchanging some bits of information (for example, the current user) between sessions.

+4
source

The usual suggestion when working with $_SESSION is that session_start (); called at the top of all your PHP scripts, first of all.

Example:

 <?php // file1.php session_start(); // other stuff... $_SESSION['user'] = 'josh'; ?> <?php // file2.php session_start(); // other stuff... echo $_SESSION['user']; // should print "josh" ?> 
0
source

All Articles