How to pass a variable as key $ _POST in PHP?

How to pass a variable as the key value of the $ _POST array in PHP? Or is it impossible?

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

thanks

+6
source share
4 answers
 $_POST['key'] = "foo"; echo $_POST['key']; 

If I understand correctly, you want to set the $_POST key.

+9
source

If I get you right, you want to transfer the variable from one php file to another through a message. There are several ways to do this.

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 press 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 as in 1., and $return will contain all the output generated by target.php .

3. Via AJAX (jQuery (JavaScript))

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

Same as 2., but now data contains output from target.php .

+14
source

Yes, yes, you can:

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

It works just like 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 the data and adding to the variable-im a loop of a predefined list of variables and storing them in variables ...

I changed the method of obtaining data

0
source

Source: https://habr.com/ru/post/900900/


All Articles