Adamssef
Adamssef

Reputation: 95

PHP unserialization of 2D array element does not work as expected

I know there were some similar questions here, but none of them seems to me be exactly what my problem is about or understanding them required more advanced knowledge than I have.

What I try to do:

My attempt is described below

if ($_SERVER["REQUEST_METHOD"] === 'POST') {

    $name = $_POST['name'];
    $surname = $_POST['surname'];
    $age = $_POST['age'];

    $assocArray = ['name' => $_POST['name'], 'surname' => $surname, 'age' => $age];

    $assocArraySerialized = serialize($assocArray);

    $_SESSION += ['etap1' => $assocArraySerialized];

    echo unserialize($_SESSION['etap1']['name']);
}

When I try to echo the item I receive:

I checked whether the $_POST works and when I echo $_POST['name'] I can see the desired value. When I var_dump the $_SESSION i can see that it got serialized correctly.

How can I have the same restoring data from $_SESSION?

Upvotes: 1

Views: 30

Answers (1)

Ani
Ani

Reputation: 42

Instead of this echo unserialize($_SESSION['etap1']['name']); try

$var = unserialize($_SESSION['etap1']);
echo $var['name'];

Upvotes: 2

Related Questions