how to pass array through hidden field

ppp picture ppp · Nov 21, 2010 · Viewed 88.4k times · Source

here my code

$order[$j][0]="Euclidean Geomethiyil Kodpagugal";
$order[$j][1]=$q16;
$j++;

hidden field-

<input type="hidden" name="hdnTotal" value="<?php echo $gtot; ?>">
<input type="hidden" name="hdnOrder" value="<?php echo $order; ?>">
<input type="submit" value="Place Order">

hdnTotal value is coming in next page but hdnOrder is not. print($_POST['hdnOrder']) print only Array on screen.

Answer

Paul Dixon picture Paul Dixon · Nov 21, 2010

You can either serialize the array, or use lots of hidden fields. Alternatively, store this in a session.

Serializing the array

To serialize, you'll use just one hidden field. This is a useful technique if your array contains non-scalar data.

 $data=serialize($order); 
 $encoded=htmlentities($data);
 echo '<input type="hidden" name="order" value="'.$encoded.'">';

When this value comes back, you need to unserialize it to get your array back out. While easy, I wouldn't recommend this unless you have some additional mechanism to prevent tampering, like a security hash, otherwise anyone can inject any PHP data structure they like!

A hash might be done like this:

 $data=serialize($order); 
 $encoded=htmlentities($data);
 $hash=md5($encoded.'SecretStringHere');
 echo '<input type="hidden" name="order" value="'.$encoded.'">';
 echo '<input type="hidden" name="order_hash" value="'.$hash.'">';

Now, when the data comes back, before you unserialize, you generate the hash again and check it matches the hash value from the form. If it doesn't match, someone tampered with the data. If it does match, then you know that whatever generated the data also knows your secret string. Which should be just you!

Finally, if it will be useful for Javascript to understand the array data, then using JSON encode/decode functions of PHP would be more appropriate.

Multiple hidden fields

Assuming a simple array consisting of scalar values, you can use lots of hidden fields

 foreach($order as $idx=>$value)
 {
      $name=htmlentities('order['.$idx.']');
      $value=htmlentities($val);
      echo '<input type="hidden" name="'.$name.'" value="'.$value.'">';

 }

This has the advantage that PHP will automatically recreate this as an array for you.

Because your array is 2 dimensional, to use this technique you'll need an inner loop for the second dimension. An exercise for the reader....

Using a session

Perhaps the easiest of the three....

session_start();

$_SESSION['order']=$order;

Once set, the array is available after you've called session_start(). This has the advantage that it never leaves the server, but will of course disappear after a period of inactivity (24 minutes is the default)