PHP: Array as value of hidden form?

Armitage

Banned
Feb 23, 2001
8,086
0
0
I need to send an associative array through a hidden form field.
Are there library functions that can do this for me?
pack/unpack & serialize/unserialize don't seem to be what I need.
Thanks
 

Gaunt

Senior member
Aug 29, 2001
450
0
0
I wrote a post, came up with an alternative solution, and then deleted the post... I think I have something you can use.

Originally I didn't think this could be done, and I had suggested using a database and serializing the array into a database record, with a unique identifier, and passing the identifer in the hidden field so you could unserialize the array.

Instead of doing that, if you serialize the array, and make the contents of the hidden field equal to the serialized result of the array, you should be able to unserialize from that form field on the next page and get your array back. Serializing an object makes it into a string, so you shouldn't have any problems putting that into a hidden form field, unless there is some limitation on the hidden form field I am unaware of. Of course, there may be a limit on the size of the array that can be passed using this method.

 

Armitage

Banned
Feb 23, 2001
8,086
0
0
Ok, serialize does work, but you also need to encode it to escape the special characters, etc.

Here's how I got it to work:

On the page with the hidden form field:

$data = serialize($data);
$data = rawurlencode($data);

then pass $data through the hidden form field

on the target page:

$data = $_POST['data'];
$data = rawurldecode($data);
$data = unserialize($data);

Thanks!
 

Superwormy

Golden Member
Feb 7, 2001
1,637
0
0
Can't you just use multiple hidden form fields?

<input type="hidden" name="myarray[keyone]" value="my value" />
<input type="hidden" name="myarray[keytwo]" value="my second value" />
<input type="hidden" name="myarray[keythree]" value="the third value" />
 

Gaunt

Senior member
Aug 29, 2001
450
0
0
I had a feeling it might have to be encoded, but I wasn't sure if there were any special characters in the serialization stuff. Atleast it works, and I've learned something as well. :)
 

Armitage

Banned
Feb 23, 2001
8,086
0
0
Originally posted by: Superwormy
Can't you just use multiple hidden form fields?

<input type="hidden" name="myarray[keyone]" value="my value" />
<input type="hidden" name="myarray[keytwo]" value="my second value" />
<input type="hidden" name="myarray[keythree]" value="the third value" />

You could, but it gets tedious & error prone. And you'd have two more places to fix every time you add to or change the array.
And you may have a case where you want to use the same code for a variety of input arrays.