如何在PHP中将变量作为$ _POST键传递?

时间:2011-11-06 20:52:02

标签: php variables

如何在PHP中将变量作为$ _POST数组键值传递?或者是不可能的?

$test = "test";
echo $_POST[$test];

由于

4 个答案:

答案 0 :(得分:14)

如果我说得对,你想通过post将一个变量从一个php文件传递到另一个php文件。这可以通过多种方式确定。

<强> 1。使用HTML表单

<form action="target.php" method="post">
  <input type="text" name="key" value="foo" />
  <input type="submit" value="submit" />
</form>

如果您点击提交按钮,$_POST['key']中的target.php将包含'foo'

<强> 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); 

1。相同,$return将包含target.php生成的所有输出。

第3。通过AJAX(jQuery(JavaScript))

<script>
$.post('target.php', {key: 'foo'}, function(data) {
  alert(data);
});
</script>

2。相同,但现在data包含target.php的输出。

答案 1 :(得分:9)

$_POST['key'] = "foo";
echo $_POST['key'];

如果我理解正确,您需要设置$_POST密钥。

答案 2 :(得分:4)

是的,是的,你可以:

$postName = "test";
$postTest = $_POST[$postName];
$_POST["test"] == $postTest; //They're equal

答案 3 :(得分:0)

就像你说的那样......

示例:

// 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]);
?>

根据评论和downvotes更新....

我不是,正如下面在循环所有数据并添加到变量的注释中所建议的那样 - 我循环预先确定的变量列表并将它们存储在变量中......

我已经改变了获取数据的方法

相关问题