如何在 PHP 中将变量作为 $_POST 键传递?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8030301/
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
How to pass variable as $_POST key in PHP?
提问by Dietpixel
How can you pass a variable as the $_POST array key value in PHP? Or is it not possible?
如何在 PHP 中将变量作为 $_POST 数组键值传递?或者不可能?
$test = "test";
echo $_POST[$test];
Thanks
谢谢
回答by Quasdunk
If I get you right, you want to pass a variable from one php-file to another via post. This sure is possible in several ways.
如果我没看错,您想通过 post 将一个变量从一个 php 文件传递到另一个 php 文件。这肯定可以通过多种方式实现。
1. With an HTML-form
1. 使用 HTML 表单
<form action="target.php" method="post">
<input type="text" name="key" value="foo" />
<input type="submit" value="submit" />
</form>
if you click on the submit-button, $_POST['key']
in target.php
will contain 'foo'
.
如果您单击提交按钮,则$_POST['key']
intarget.php
将包含'foo'
.
2. Directly from PHP
2.直接来自PHP
$context = stream_context_create(array(
'http' => array(
'method' => 'POST',
'header' => "Content-type: text/html\r\n",
'content' => http_build_query(array('key' => 'foo'))
),
));
$return = file_get_contents('target.php', false, $context);
Same thing as in 1., and $return
will contain all the output produced by target.php
.
与1.相同,$return
将包含target.php
.产生的所有输出。
3. Via AJAX (jQuery (JavaScript))
3. 通过 AJAX (jQuery (JavaScript))
<script>
$.post('target.php', {key: 'foo'}, function(data) {
alert(data);
});
</script>
Same thing as in 2., but now data
contains the output from target.php
.
与2.相同,但现在data
包含来自target.php
.
回答by Dimitar Marinov
$_POST['key'] = "foo";
echo $_POST['key'];
If I understood right, you want to set a $_POST
key.
如果我理解正确,你想设置一个$_POST
键。
回答by JCOC611
Yes, yes you can:
是的,是的,您可以:
$postName = "test";
$postTest = $_POST[$postName];
$_POST["test"] == $postTest; //They're equal
回答by Manse
Works just as you said ...
就像你说的那样工作......
Example :
例子 :
// create an array of all the GET/POST variables you want to use
$fields = array('salutation','fname','lname','email','company','job_title','addr1','addr2','city','state',
'zip','country','phone','work_phone');
// convert each REQUEST variable (GET, POST or COOKIE) to a local variable
foreach($fields as $field)
${$field} = sanitize($_POST[$field]);
?>
Updated based on comments and downvotes ....
根据评论和反对票更新....
I am not, as was suggested below in the comments looping all data and adding to a variable - im looping pre-determined list of variables and storing them in variables ...
我不是,正如下面在循环所有数据并添加到变量的评论中所建议的那样 - 我循环预先确定的变量列表并将它们存储在变量中......
I have change the method of getting the data
我改变了获取数据的方法