Passing array by post form hidden field

hi

The problem is that I would like to pass an entire array as a hidden
input field from one php script to another. like this

<form…>
$array[0] = ‘abc’;
$array[1] = ‘xyz’;

// hidden field for passing the array.

</form>

how can i do this?

you could use serialize() and base64_encode(), although the manual warns against using unserialize() on data which was submitted by a user. the only danger i can think of is that the user could pass an object to your php script and unserialize() would instantiate it if conditions were correct. there could be more reasons though, it might be wise to heed thier warnings.

an alternate method could potentially be crafted by using implode() and explode()

but i think storing the values in a php session would be a better way to go. no risk of data manipulation that way.

You might find it useful to look at serialization, this will allow you to represent your array as a string which you can use in a hidden form field. The page which processes the form submission should unserialize the string to give you your array back again.

http://php.net/serialize

anybody can give me any practical code example?

wait… making the array and passing it as an array doesnt work for you?

<input type="hidden" name="myArray[0]" value="abc">
<input type="hidden" name="myArray[1]" value="xyz">


$myArray = $_POST['myArray'];

if(isarray($myArray)) {

  // ... then do something with it

    foreach($myArray as $aselection){

       echo "$aselection<br>";

    }

}


I always remind myself to do an isarray() check – just the other day, I created a select list in a form, if the user didn’t select anything, then php would toss up an error when it hit foreach() like in the example above. Reason being, if nothing is selected in the form, it doesn’t pass myArray during the post.

Btw, when I’m writing any script that takes input from a form, I usually put the following code at the top during testing. Thus, I can visually make sure all the form fields are being carried over.



// dump all posted values

foreach ( $_POST as $key => $value ) {
 print $key . " " . "=" . " " . $value;
 print "<br>";
}