Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass variable as $_POST key in PHP?

Tags:

variables

php

How can you pass a variable as the $_POST array key value in PHP? Or is it not possible?

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

Thanks

like image 787
Dietpixel Avatar asked Nov 06 '11 20:11

Dietpixel


People also ask

What is $_ POST [] in PHP?

PHP $_POST is a PHP super global variable which is used to collect form data after submitting an HTML form with method="post". $_POST is also widely used to pass variables. The example below shows a form with an input field and a submit button.

What does ?: Mean in PHP?

The Scope Resolution Operator (also called Paamayim Nekudotayim) or in simpler terms, the double colon, is a token that allows access to static, constant, and overridden properties or methods of a class.

Which variable will be used to pick the value using POST method?

The $_REQUEST variable The PHP $_REQUEST variable can be used to get the result from form data sent with both the GET and POST methods.

How does $_ POST work?

The $_POST variable collects the data from the HTML form via the POST method. When a user fills the data in a PHP form and submits the data that is sent can be collected with the _POST Method in PHP. The Post Method transfers the information via the Headers.


2 Answers

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.

1. With an HTML-form

<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'.

2. Directly from 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.

3. Via 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.

like image 168
Quasdunk Avatar answered Oct 19 '22 05:10

Quasdunk


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

If I understood right, you want to set a $_POST key.

like image 22
Dimitar Marinov Avatar answered Oct 19 '22 04:10

Dimitar Marinov