How to pass variable as $_POST key in PHP?

后端 未结 4 1396
北恋
北恋 2020-12-31 22:24

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

相关标签:
4条回答
  • 2020-12-31 22:47

    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

    0 讨论(0)
  • 2020-12-31 22:48

    Yes, yes you can:

    $postName = "test";
    $postTest = $_POST[$postName];
    $_POST["test"] == $postTest; //They're equal
    
    0 讨论(0)
  • 2020-12-31 22:57

    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.

    0 讨论(0)
  • 2020-12-31 23:11
    $_POST['key'] = "foo";
    echo $_POST['key'];
    

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

    0 讨论(0)
提交回复
热议问题