php 如何通过隐藏字段传递数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4237090/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 12:21:55  来源:igfitidea点击:

how to pass array through hidden field

phparrayshidden

提问by ppp

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">

hdnTotalvalue is coming in next page but hdnOrderis not. print($_POST['hdnOrder'])print only Arrayon screen.

hdnTotal价值进入下一页,但hdnOrder不是。print($_POST['hdnOrder'])Array在屏幕上打印。

回答by Paul Dixon

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 unserializeit 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!

当此值返回时,您需要对其进行反序列化以将数组取出。虽然很简单,但我不会推荐这个,除非你有一些额外的机制来防止篡改,比如安全哈希,否则任何人都可以注入他们喜欢的任何 PHP 数据结构!

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/decodefunctions of PHP would be more appropriate.

最后,如果对 Javascript 理解数组数据有用,那么使用PHP 的JSON编码/解码功能会更合适。

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 arrayfor you.

这样做的好处是 PHP 会自动为您重新创建它作为数组

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)

设置后,该数组在您调用 session_start() 后可用。这样做的好处是它永远不会离开服务器,但在一段时间不活动后当然会消失(默认为 24​​ 分钟)

回答by Eric Anderson

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.

序列化为单个字段的另一种解决方案是序列化为多个隐藏字段。我写了一个通用函数来做到这一点。此功能和示例在GistHub 的 Gist 服务中进行管理。在那里检查最新版本,但为了方便起见复制到这里。

<?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]">

回答by Pascal Qyy

Try json_encode:

试试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:

为了取回它,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.

此解决方案的好处是您将能够使用 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.

如果不是为了在客户端操作您的数据,您会创建一个不必要的数据往返,您可以使用PHP 会话轻松地将其保留在服务器端。

回答by Alin Purcaru

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

如果您有非标量值,您应该序列化和反序列化它们。您有多种选择:

  1. PHP's serializeand unserialize
  2. JSON encodeand decode
  1. PHP 的序列化和反序列化
  2. JSON编码解码

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

作为一般规则,如果在 HTML 中放置任何值,则需要对其 HTML 特殊字符进行编码

Use case:

用例:

<?php
$arr = unserialize($_REQUEST['arr']);
?>
<input type="hidden" name="arr" value="<?php echo htmlentities(serialize($arr)); ?>" />

回答by Dan Grossman

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 serializefunction, then unserialize$_POST['order'] to get the original array back

1)用PHP的serialize函数将数组序列化为字符串,然后unserialize$_POST['order']取回原数组

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

2)将它传递给您必须生成的一系列表单字段

<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?

如果您不控制表单,那么您提交的任何内容都可能期望 hdnOrder 中的某些特定内容......它是什么?

回答by uberweb

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.

从它的声音来看,您只想将数据从表单的一页传递到另一页。如果是这样,请使用 PHP 会话。它更容易实施、更高效、更安全。