PHP 没有使用给定的变量

PHP doesn't use the given variable

我的HTML表格:

<form action="lambda.php" method="post">
<label><input type="number" name="intfield" id="intfield"/></label>
<input type="submit" value="Go!"/>
</form>

部分PHP代码:

$hello = intval($_POST["intfield"]);

$client = LambdaClient::factory(array(
            'version' => "latest",
            'credentials' => array(
                'key' => 'blurred',
                'secret' => 'blurred'
            ),
            'region' => 'us-west-2'
        ));

$response = $client->invoke([
    'FunctionName' => 'helloworld2',
    'InvocationType' => 'RequestResponse',
    'Payload' => '{"key1":"$hello"}',
        ]);

echo($response['Payload']->__toString());
echo $hello;

基本上我想输入一个数字到 HTML 的形式,然后将其提供给 PHP 代码。 PHP 文件应将数字发送到 Lambda(Amazon Web 服务)中的函数。

我的 Lambda 函数和 PHP 没问题。如果我像这样在 PHP 中硬编码数字,它就可以正常工作:

'Payload' => '{"key1":"7"}',

但显然我想将它与变量一起使用。 PHP 代码中的最后一个 echo 显示了正确的数字。你能找到我的 PHP 代码中的错误吗?谢谢!

由于字符串引号,变量 $hello 在您的代码中被视为字符串:

你可以这样测试:

$hello = intval(1); // initialize a variable.

比作数组:

$response = [
'FunctionName' => 'helloworld2',
'InvocationType' => 'RequestResponse',
'Payload' => '{"key1":"$hello"}',
];

print_r($response);

结果:

Array
(
    [FunctionName] => helloworld2
    [InvocationType] => RequestResponse
    [Payload] => {"key1":"$hello"}
)

上面提到的结果告诉你代码中的每一个错误 现在,当我修复引号问题并使用 json_encode() 作为您想要的输出时:

<?php
$hello = intval(1);
$response = [
'FunctionName' => 'helloworld2',
'InvocationType' => 'RequestResponse',
'Payload' => json_encode(array('key1'=>$hello)),
];
echo "<pre>";
print_r($response);
?>

它给了我正确的结果:

Array
(
    [FunctionName] => helloworld2
    [InvocationType] => RequestResponse
    [Payload] => {"key1":1}
)

PHP中的单引号字符串不展开变量。因此,您将字符串 '$hello' 而不是 $hello 的值传递给服务。通过将 is 更改为 "{\"key1\":\"{$hello}\"}" 它将传递变量的值。

始终使用单引号来构成常量字符串。如果您需要像 "\n" 这样的转义或像 "test: {$test}".

这样的扩展,请使用双引号

始终验证客户端传递的字符串,以免造成安全问题。