Skip to content
Advertisement

Setting a session in steps

Is it possible to set multiple session elements to the same session at different times? I have 2 classes and each class should set 2 session elements. What I’m getting back is an empty array. I am using session_start() on each page.

Also, I can set the session successfully from within a single class, but get an empty array back when setting from each class.

// User class
$_SESSION['user'] = array('id' => 1);
$_SESSION['user'] = array('name' => 'Tim Miller');

// Part class
$_SESSION['user'] = array('model' => '12311');
$_SESSION['user'] = array('part' => 'AA34F');

EDIT:

Here is the array I would like to create:

Array (
  [user] => Array (
    [id] => 1
    [name] => Tim Miller
    [model] => 12311
    [part] => AA34F
    [order] => 119026
    [serial] => 12001923S3
  )
)

Elements 0 and 1 should be set in the user class Elements 2-3 should be set in the part class Elements 4-5 should be set in the serial class

Advertisement

Answer

You can set it but bit different approach need to be used. You can create an array of sessions with different values.

You have to write session_start() on top of each file where you need to use session.

session_start();

// User class
$_SESSION['user'][] = array('id' => 1);
$_SESSION['user'][] = array('name' => 'Tim Miller');

// Part class
$_SESSION['user'][] = array('model' => '12311');
$_SESSION['user'][] = array('part' => 'AA34F');

print_r( $_SESSION['user'] );

Output looks like:

Array
(
    [0] => Array
        (
            [id] => 1
        )

    [1] => Array
        (
            [name] => Tim Miller
        )

    [2] => Array
        (
            [model] => 12311
        )

    [3] => Array
        (
            [part] => AA34F
        )
)

It’s upto you how do you want to crate this array.

EDIT:

To get your desire format output and add values to array later in different files you can give a try like:

// Your code here!
session_start();

// User class
$_SESSION['user'][] = array('id' => 1, 'name' => 'Tim Miller');

// Part class
$key = -1
$key = array_search( 1, array_column($_SESSION['user'], 'id') );
// Here 1 in array_search is id of user your can use $id to add data to correct user's by id.

if( $key > -1 ) {
    $_SESSION['user'][ $key ] = array_merge( $_SESSION['user'][ $key ], array('model' => '12311', 'part' => 'AA34F') );
}


print_r( $_SESSION['user'] );

This will give you following output:

Array
(
    [0] => Array
        (
            [id] => 1
            [name] => Tim Miller
            [model] => 12311
            [part] => AA34F
        )
)
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement