Basil Zuberi
Basil Zuberi

Reputation: 93

Passing a multi-dimensional array using sessions in PHP

I am currently trying to pass a multidimensional array through sessions while also being able to dynamically add/remove from it (it is a wish-list). The index of the array will be the ID of an item I am adding to the array. I've tried serialization, using variables instead of the actual session and none of it worked properly for me.

My issue is that my array will not pass from page 1 to page 2. Page 1 is what happens when the user clicks any "add to wish-list" button

I searched up on Google and wrote something similar to this:

page 1:

session_start();
$_SESSION['wishlist'] = array();
$id = $_GET['id'];
$imageFileName = $_GET['ImageFileName'];
$title = urldecode($_GET['PictureName']);

$_SESSION['wishlist'][$id]=array("id"=>$id,"title"=>$title,"imageFileName"=>$imageFileName); // Here im making the multidimensional array

$_SESSION['wishlist'] = $_POST; //found this way on Stackoverflow

header('Location:view-wish-list.php'); //move to second page

page 2: trying to start session and print out the array to test:

session_start();


var_dump($_SESSION['wishlist']);

Var Dump gives me array(0) { }

Any help would be appreciated. Thank you.

Upvotes: 0

Views: 154

Answers (1)

ArSeN
ArSeN

Reputation: 5258

You have to commit (write) the session before redirection or the second request may occur before the session data is available on the server:

session_write_close();
header('Location:view-wish-list.php'); //move to second page

Upvotes: 1

Related Questions