how to pass array through hidden field
Asked Answered
C

7

22

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.

Crumpet answered 21/11, 2010 at 8:50 Comment(3)
That's because order is an array, not a specific value.Excitable
Have you ever thought of using a session?Distill
Why is this not accepted ???Apposite
L
45

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)

Larondalarosa answered 21/11, 2010 at 8:57 Comment(3)
I don't understand your solution: it will be pretty hard to manipulate data at client side with that, so what send it rather than keep it at client side?Chladek
The OP doesn't appear to require any client side manipulation, only to preserve the data across a form post. However, if client side manipulation were required, then JSON would be more appropriate, as noted in my answer.Larondalarosa
So why send DATA to the client just for he resend it to the server, if it's neither for handle it neither display it?Chladek
G
11

An alternative solution to serializing to a single field is to serialize to multiple hidden fields. I wrote a generic function to do this. This function and the examples are being managed at GistHub's Gist service. Check there for the latest version but copied here for convenience.

<?php
# https://gist.github.com/eric1234/5802030

function array_to_input($array, $prefix='') {
  if( (bool)count(array_filter(array_keys($array), 'is_string')) ) {
    foreach($array as $key => $value) {
      if( empty($prefix) ) {
        $name = $key;
      } else {
        $name = $prefix.'['.$key.']';
      }
      if( is_array($value) ) {
        array_to_input($value, $name);
      } else { ?>
        <input type="hidden" value="<?php echo $value ?>" name="<?php echo $name?>">
      <?php }
    }
  } else {
    foreach($array as $item) {
      if( is_array($item) ) {
        array_to_input($item, $prefix.'[]');
      } else { ?>
        <input type="hidden" name="<?php echo $prefix ?>[]" value="<?php echo $item ?>">
      <?php }
    }
  }
}

Here is some example usage:

Basic Associative Array

echo array_to_input(array('foo' => 'bar', 'cat' => 'dog'));

Will output:

<input type="hidden" value="bar" name="foo">
<input type="hidden" value="dog" name="cat">

Associative Array with Nested Indexed Array

echo array_to_input(array('foo' => 'bar', 'cat' => 'dog', 'list' => array('a', 'b', 'c')));

Will output:

<input type="hidden" value="bar" name="foo">
<input type="hidden" value="dog" name="cat">
<input type="hidden" name="list[]" value="a">
<input type="hidden" name="list[]" value="b">
<input type="hidden" name="list[]" value="c">

Associative Array with Nested Associative Array

echo array_to_input(array('foo' => array('bar' => 'baz', 'a' => 'b'), 'cat' => 'dog'));

Will output:

<input type="hidden" value="baz" name="foo[bar]">
<input type="hidden" value="b" name="foo[a]">
<input type="hidden" value="dog" name="cat">

Go Crazy

echo array_to_input(array('a' => array('b' => array('c' => array('d' => 'e')))));

Will output:

<input type="hidden" value="e" name="a[b][c][d]">
Glory answered 18/6, 2013 at 1:50 Comment(0)
C
9

Try json_encode:

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

and for get it back, json_decode:

print(json_decode($_POST['hdnOrder']));

The bonus of this solution is that you will able to manipulate your array at client side easily with JavaScript.

But why do you want to do that ?

If it is not for manipulate your data at client side, you create an an unnecessary round trip of your data, that you can easily keep at server side with PHP sessions.

Chladek answered 21/11, 2010 at 8:56 Comment(2)
There's no reason to use JSON if you're not working with JavaScript; PHP has its own serialization format. Those functions are not available in PHP 5.1.x or older which many web hosts still use. You can't stick JSON directly into HTML like that either, since it contains double quotes, blank lines, and other characters that need to be encoded.Contredanse
As I said, with JSon, it's possible to manipulate data at client side with Javascript. That's not possible with PHP serialization, and why send data to the client if the client just send them back as is?Chladek
M
5

If you have non-scalar values you should serialize and unserialize them. You have multiple options:

  1. PHP's serialize and unserialize
  2. JSON encode and decode

As a general rule, if you put any value in HTML you need to encode its HTML special chars.

Use case:

<?php
$arr = unserialize($_REQUEST['arr']);
?>
<input type="hidden" name="arr" value="<?php echo htmlentities(serialize($arr)); ?>" />
Melisa answered 21/11, 2010 at 8:58 Comment(0)
C
2

Where's this form going and why does it need a multidimensional array to be passed as part of the form?

How you're going to do this depends on whether you control the page receiving the form. If you do, you have a couple options:

1) Serialize the array to a string with PHP's serialize function, then unserialize $_POST['order'] to get the original array back

2) Pass it through an array of form fields you'll have to generate

<input type="hidden" name="hdnOrder[0][0]" value="Something" />
<input type="hidden" name="hdnOrder[0][1]" value="Something else" />

If you don't control the form then whatever you're submitting to probably expects something specific in hdnOrder... what is it?

Contredanse answered 21/11, 2010 at 8:57 Comment(1)
Why is my solution terrible when you suggested the same solution, except you used JSON encoding instead of PHP's own serialization?Contredanse
U
0

For java servlets

arr={"Apple","Bannana","Cherry","Dragan"};
for(int i=0;i<4;i++)
    out.println("<input type=hidden name=fruits value="+arr[i]+">");
Unsustainable answered 24/6, 2020 at 9:37 Comment(2)
As an example array value is shown here, array values can be obtained from another page using the following statement. String arr[] = req.getParameterValues("trees");Unsustainable
Please edit your answer to add additional information. It's much more likely to get lost in comments.Scarface
H
-1

From the sounds of it you just want to pass data from one page of a form to another. If so use a PHP Session. It's much easier to implement, more efficient and more secure.

Hepsiba answered 21/11, 2010 at 14:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.