user3284629
user3284629

Reputation: 13

Save $_POST to $_SESSION

I need to save complete $_POST to $_SESSION and after back it to $_POST, I find code for this:

// 1.save
$_SESSION['POST'] = $_POST;

// 2.ERROR HERE - its return empty array
var_dump($_SESSION['POST']);

// 3.reload page

// 4.back all data to $_POST
$_POST = $_SESSION['POST'];

Of course at the top of file I have session_start(); and I use working $_SESSION variables in my file without any problems.

Thanks for your help.

Upvotes: 0

Views: 3388

Answers (2)

helion3
helion3

Reputation: 37361

Until we see more code I'll assume you're not checking whether or not $_POST contains data. If it's empty (will always be unless there's actual POST data), it's going to reset the $_SESSION every request.

Check that $_POST is not empty (there are multiple ways):

if( !empty($_POST) ) or if( count($_POST) ) etc

Upvotes: 1

ʰᵈˑ
ʰᵈˑ

Reputation: 11375

If you're wanting to store all of $_POST into the $_SESSION, adopt the following;

$_SESSION['POST'] = serialize($_POST); #Copy _POST to _SESSION
$_POST = unserialize($_SESSION['POST']); #Copy it back.
  • Additionally, you could adopt json_encode and decode accordingly.

Also, adopt what helion3 said and check that _POST actually has keys/values before you assign it to the _SESSION

Here's a quick demonstration.

I have a _POST with the following data,

Array ( 
 [name] => Frank 
 [animal] => Penguin 
)

And I use the script above to copy it to a _SESSION making the value;

1a:2:{s:4:"name";s:5:"Frank";s:6:"animal";s:7:"Penguin";}

I then copy it back to _POST, and becomes what it was originally

Array ( 
 [name] => Frank 
 [animal] => Penguin 
)

Here's a demonstration script.

<?php

session_start();

$_POST = array();
$_POST['name'] = "Frank";
$_POST['animal'] = "Penguin";

$_SESSION['POST'] = serialize($_POST);
print_r($_SESSION['POST']);

unset($_POST); # _POST has been destroyed

//Now rebuild _POST
$_POST = unserialize($_SESSION['POST']);
print_r($_POST);

Upvotes: 3

Related Questions