用PHP中的用户输入比较变量始终返回false

时间:2019-06-24 06:37:17

标签: php string if-statement compare

我正在制作一个比较两个变量的验证页

第一个是先前从python脚本生成的随机代码,并将结果带到php变量下,其名称为输出的$ code示例(8063D0A7),它是8个数字和字母的字符

第二个是用户输入($ verf)

当用户单击“提交”时,应比较($ code)和($ verf)(如果为真),然后转移到其他页面(如果没有,则重试)

我已经尝试了很多方法,但是无论如何,在任何输入下,它总是显示

<?php
session_start(); ///starts a session and getting the variables from another page 

echo "E-mail has been sent to " ;
echo $_SESSION['email'];  ///gets $email from another page


echo $email , "   ";
echo $_SESSION['code'];  ///gets the $code from another page


$email = escapeshellarg($_SESSION['email']);  ///make an arg to put in bash script


$code = escapeshellarg($_SESSION['code']);


$addr = shell_exec("./test.sh $email $code"); ///execute bash script to send $code to $email


?>
<!DOCTYPE HTML>  
<html>
<body>  
<h2>E-mail Verfication</h2>
<form method="post" action="">  
Name: <input type="string" name="verf" value="">
  <br><br>
  <input type="submit" name="submit2" value="Submit">  
</form>

<?php
if (isset($_POST['submit2'])) {
    $verf = $_POST['verf'];
    if ($verf == $code) {
        echo "Correct!";
         header('Location: 12.php');
    } else { 
        echo "Wrong!";

    }

} else {
    echo "please fill the verification";
}



 echo $verf;
 echo $code;

?>

</body>
</html>

我认为识别变量存在问题,例如,将$ code作为字符串,将$ verf作为其他类型的输入,因此它将始终为假,我不知道我是PHP帮助PLZ的新手。 :D

1 个答案:

答案 0 :(得分:1)

问题很简单-这是因为您使用escapeshellarg(),它会在字符串周围添加单引号,并用引号/转义符将所有现有的单引号引起来(请检查手册:PHP escapeshellarg

所以,就您而言:

// lets say:
$_SESSION['code']="abc";

// then you do:
$code = escapeshellarg($_SESSION['code']);

// this means that now, $code is actually "'abc'" instead of "abc"
echo $code;

// so, if
$verf = "abc";

// then of course, $code is NOT the same with $verf;

echo $code == $verf ? "correct" : "incorrect";

因此,在您的情况下,您应该更改此行:

//$verf = $_POST['verf'];
$verf = escapeshellarg($_POST['verf']);

下次,尝试通过回显$ verf vs $ code对其进行调试。

编辑。对评论的回应:

要删除数据中的空白,可以使用:trim()

$code = "  A1B3 ";
$code = trim($code);
echo $code;
//A1B3

或者,要删除所有不需要的字符(例如非A-Z或0-9的字符),可以使用:preg_replace()

$code = "  A1B3?!#@! ";
$code = preg_replace("/[^A-Z0-9]/", "", $code);
echo $code;
//A1B3