$ _POST [$ variable]不起作用[关闭]

For input form I need random input name and id

I created random values $token_hash = random

Then input field

 <input type="hidden" name="' .$token_hash .'" id="' .$token_hash .'" value="some_value">

Next above input form is php code to check what values get from form

 echo $_POST[$token_hash] .' $_POST[$token_hash]<br>';

Problem is that $_POST[$token_hash] echo blank value (no value)....

I tried also $_POST[' .$token_hash .'] but do not work.

Other $_POST works, but they are like $_POST['some_value']


Seems finally get solution. Do not understand why it did not work before. If useful for someone else. Here is solution.

Create random value $token_hash = sha1(uniqid($time_when_form_submitted .'token' .$_SERVER["REMOTE_ADDR"]));

Then create session $_SESSION['token_hash'] = $token_hash;

Then pass session to input

echo '<input type="hidden" name="' .$_SESSION['token_hash'] .'" id="' .$_SESSION['token_hash'] .'" value="' .$_SESSION['token'] .'">'

Then get session value from input. This code must be above all previos $token_hash_from_input = $_SESSION['token_hash'];

Then with $_POST[$token_hash_from_input]) get input value

you need to do it like this,

$_POST["token_hash"]

if that token_hash has really been posted, you will get one

You want the name of the input to be 'token_hash' and the value to be your random value.

<input name="token_hash" value="<?php echo $token_hash; %>" type="hidden" />

Now you can access the token hash on form submit:

$token_hash = $_POST['token_hash'];

Since you're generating a random value, you can't expect $_POST[$token_hash] to work.

When you POST your form, your PHP is random generating your $token_hash value AGAIN. So you should put your random generated value in a "value" attribute.

     <input name="token_hash" value="<?php echo $token_hash; ?>" type="hidden" />

and you can get it with $_POST['token_hash'] when you post your form.

You'll need something like sessions to persist values across requests, e.g.

session_start();
$_SESSION['token_hash'] = $token_hash;

then retrieve it in the next page

session_start();
$token_hash = $_SESSION['token_hash'];

@All I assume the questioner wants to have a random post field name and value


Note that the value of $token_hash will change on each request. There is no persistance unless you save that value in a session or database. I don't what exactly you are trying to do so its hard to give advices.

But this code example may show how to access a random $_POST index:

<input type="hidden" name="token_<?php echo uniqid();?>" value="<?php uniqid()?>" />

Then get the value using foreach:

foreach($_POST as $key => $value) {
    if(strpos($key, 'token_') !== FALSE) {
        echo 'the token is ' . $value;
    }
}