PHP验证错误逻辑错误

时间:2018-03-27 02:12:15

标签: php

我在PHP中有一个注册表单,我正在对我的PHP页面执行ajax请求以验证所有字段并将数据插入到我的数据库中。但是一次又一次,它在第一个回声声明“请输入所有字段”中给我一个错误。虽然我填写输入字段。 非常感谢。请告诉我以下代码是否可以安全使用。

 $username= filter_input(INPUT_POST,"userName", FILTER_SANITIZE_STRING);
$email=filter_input(INPUT_POST,"userEmail", FILTER_VALIDATE_EMAIL);
$password=filter_input(INPUT_POST,"userpassword",FILTER_SANATIZE_STRING);
$verifyPassword=filter_input(INPUT_POST,"verifyPassword",FILTER_SANATIZE_STRING);


if(empty($username) || empty($email) || empty($password) || empty($verifyPassword)){
    echo "Please enter all the fields";
}
else if($password !== $verifyPassword){
    echo "Password doesn't match";
}
else{
    $stmt1 = $dbh->prepare("SELECT userEmail FROM regularUser WHERE userEmail = :email");
    $stmt1->bindParam("email", $email) ;
    $stmt1->execute();
    $result1 = $stmt1->fetchAll(PDO::FETCH_ASSOC);
    $count = $result1->rowCount();
        if($count > 1)
        {
            echo "Email already exist";
        }
        else
        {
            $stmt = $dbh->prepare("INSERT INTO regularUser(userEmail,userName,userPassword) VALUES (:email,:name,:password)");  
            $stmt->bindParam("email", $email) ;
            $stmt->bindParam("name", $username) ;
            $hash = password_hash($password, PASSWORD_BCRYPT);
            $stmt->bindParam("hash_password", $hash) ;
            $stmt->execute();
            echo "success";   
        }
    }

2 个答案:

答案 0 :(得分:0)

您应该使用$username来检查$email$password$verifyPasswordstring

您可以看到它们是arrayObjectempty()

在某些情况下,Empty()不正确!

您应该使用:

    {li> Array is_null()
  • object代表string!=''
  • {li> string <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title></title> <link rel="stylesheet" href="./resources/css/style.css"> </head> <body> <header> <div class="logo"> <img src="./resources/images/img-myt-logo.jpg" alt="Our logo"> <span>My Times</span> </div> <nav> <span>World</span> <span>U.S</span> <span>Tech</span> <span>Science</span> </nav> </header> </body> </html>

答案 1 :(得分:0)

更改此

if(empty($username) || empty($email) || empty($password) || empty($verifyPassword)){
    echo "Please enter all the fields";
}
else if($password !== $verifyPassword){
    echo "Password doesn't match";
}

$errors = [];

if(empty($username)) $errors[] = 'Please enter a username';
if(empty($email)) $errors[] = 'Please enter an email';
if(empty($password)) $errors[] = 'Please enter a password';
if(empty($verifyPassword)) $errors[] = 'Please enter a verify password';
if($password !== $verifyPassword) $errors[] = 'Password doesn\'t match';

if(count($errors) > 0) echo implode("\n", $username); //or <br>

以这种方式思考,如果您无法找到哪些字段,您的最终用户也会如此。

虽然这不能解决您的问题,但它会告诉您哪个字段为空。

有很多方法可以做到这一点,但您应始终努力为用户提供尽可能多的信息,而不会干扰安全性。