【问题标题】:compare variable with user input in php always returns false将变量与php中的用户输入进行比较总是返回false
【发布时间】:2019-06-24 06:37:17
【问题描述】:

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

第一个是之前从 python 脚本生成的随机代码,并将结果带到名称为 $code 输出示例 (8063D0A7) 下的 php 变量,它是 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

【问题讨论】:

    标签: php string if-statement compare


    【解决方案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
    

    【讨论】:

    • 谢谢你现在我明白发生了什么......现在的问题是 $verf1 是 '940E8A83' 而 $code 是 '940E8A83 ' 你看开头和结尾都有一个空格我不知道它的来源的每个变量你能帮我吗?
    • 我明白了。我在回答中添加了一些解释。尝试在您的脚本中使用其中一种功能。
    猜你喜欢
    • 2017-09-16
    • 2017-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多