Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - How to send an array to another page?

Tags:

I'm trying to send an array to another page.

What I tryed before was:

page1

<input type='hidden' name='input_name' value='<?php print_r($array_name); ?>' />

And page2

<?php 
$passed_array = $_POST['input_name'];
?>

Now how do I make $passed_array act like an array?

Or do you know of any other way of solving this problem?

Thanks, Mike.

Edit: The reason I want to do it this way is because I need to avoid sessions and cookies.

like image 294
Mike Avatar asked Oct 10 '09 14:10

Mike


2 Answers

You could put it in the session:

session_start();
$_SESSION['array_name'] = $array_name;

Or if you want to send it via a form you can serialize it:

<input type='hidden' name='input_name' value="<?php echo htmlentities(serialize($array_name)); ?>" />

$passed_array = unserialize($_POST['input_name']);

The session has the advantage that the client doesn't see it (therefore can't tamper with it) and it's faster if the array is large. The disadvantage is it could get confused if the user has multiple tabs open.

Edit: a lot of answers are suggesting using name="input_name[]". This won't work in the general case - it would need to be modified to support associative arrays, and modified a lot to support multidimensional arrays (icky!). Much better to stick to serialize.

like image 141
Greg Avatar answered Oct 06 '22 05:10

Greg


You could serialize the array, which turns it into a string, and then unserialize it afterwards, which turns it back into an array. Like this:

<input type='hidden' name='input_name' value='<?php serialize($array_name); ?>' />

and on page 2:

<?php $passed_array = unserialize($_POST['input_name']); ?>
like image 29
Martijn Heemels Avatar answered Oct 06 '22 05:10

Martijn Heemels