错误输入用户输入后,PHP代码成功完成

时间:2020-02-20 20:43:47

标签: php mysql

我正在编写的应用程序中的这段代码有问题:

<?php

session_start();

include('api/dbconnect.php');

$msg = "";

if(isset($_POST['register-submit'])) {
// Now we check if the data was submitted, isset() function will check if the data exists.
    if (!isset($_POST['first_name'], $_POST['last_name'], $_POST['email'], $_POST['username'], $_POST['password'])) {
        // Could not get the data that should have been sent.
        $msg = 'Please complete the registration form';
    }
// Make sure the submitted registration values are not empty.
    if (empty($_POST['first_name']) || empty($_POST['last_name']) || /*empty($_POST['email']) ||*/ empty($_POST['username']) || empty($_POST['password'])) {
        // One or more values are empty.
        $msg = 'All fields are required for the form to be submitted';
    }

    /*if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
        die ('The email address provided is invalid');
    }*/

    if (preg_match('/[A-Za-z0-9]+/', $_POST['username']) == 0) {
        $msg = 'The username provided is invalid';
    }

    if (strlen($_POST['password']) > 20 || strlen($_POST['password']) < 5) {
        $msg = 'Password must be between 5 and 20 characters';
    }

    if ($_POST['password'] != $_POST['confirm_pwd']) {
        $msg = 'The two password provided do not match.';
    }

// We need to check if the account with that username exists.
    if ($stmt = $pdo->prepare('SELECT id, password FROM users WHERE username = ?')) {
        // Bind parameters (s = string, i = int, b = blob, etc), hash the password using the PHP password_hash function.
        $stmt->bindParam(1, $_POST['username']);
        $stmt->execute();
        // Store the result so we can check if the account exists in the database.
        if ($stmt->num_rows > 0) {
            // Username already exists
            $msg = 'Another account with this username already exists';
        } else {
            // Username doesnt exist, insert new account
            if ($stmt = $pdo->prepare('INSERT INTO users (first_name, last_name, email, username, password) VALUES (?, ?, ?, ?, ?)')) {
                // We do not want to expose passwords in our database, so hash the password and use password_verify when a user logs in.
                $password = password_hash($_POST['password'], PASSWORD_DEFAULT);
                $stmt->bindParam(1, $_POST['first_name']);
                $stmt->bindParam(2, $_POST['last_name']);
                $stmt->bindParam(3, $_POST['email']);
                $stmt->bindParam(4, $_POST['username']);
                $stmt->bindParam(5, $password);
                $stmt->execute();
                header('Location: users.php');
            } else {
                // Something is wrong with the sql statement, check to make sure users table exists with all 3 fields.
                $msg = 'There was a problem creating this account. Contact your Network Administrator.';
            }
        }
        $stmt->close();
    } else {
        // Something is wrong with the sql statement, check to make sure users table exists with all 3 fields.
        $msg = 'There was a problem creating this account. Contact your Network Administrator.';
    }
//$con->close();
}

?>

该代码应创建一个新用户并将其添加到MySQL表中。该代码正在运行,但是即使是故意的,该代码也不会产生错误。例如,如果我输入两个不同的密码,则代码认为没有问题,因此可以成功完成注册。到处都有一个$msg变量,代码需要停止并重新加载页面以在HTML表单内显示错误,以便用户可以更正它,但是它不起作用。

我在代码中看不到什么?

这是代码所属的HTML表单:

<form class="user" method="post" action="user_new.php">
  <div class="custom-control small">
    <strong class="text-danger"><?php echo $msg; ?></strong>
  </div>
  <div class="form-group row">
    <div class="col-sm-6 mb-3 mb-sm-0">
      <input type="text" class="form-control form-control-user" id="first_name" name="first_name" placeholder="First Name" autocomplete="off" required>
    </div>
    <div class="col-sm-6">
      <input type="text" class="form-control form-control-user" id="last_name" name="last_name" placeholder="Last Name" autocomplete="off" required>
    </div>
  </div>
  <div class="form-group row">
    <div class="col-sm-6 mb-3 mb-sm-0">
      <input type="email" class="form-control form-control-user" id="email" name="email" placeholder="Email Address (optional)" autocomplete="off">
    </div>
    <div class="col-sm-6">
      <input type="text" class="form-control form-control-user" id="username" name="username" placeholder="Username" autocomplete="off" required>
    </div>
  </div>
  <div class="form-group row">
    <div class="col-sm-6 mb-3 mb-sm-0">
      <input type="password" class="form-control form-control-user" id="password" name="password" placeholder="Password" autocomplete="off" required>
    </div>
    <div class="col-sm-6">
      <input type="password" class="form-control form-control-user" id="confirm_pwd" name="confirm_pwd" placeholder="Confirm Password" autocomplete="off" required>
    </div>
  </div>
  <button type="submit" name="register-submit" class="btn btn-primary btn-user btn-block" style="background-color: #a40000; border-color: #a40000;">Create User Account</button>
  <hr>
  <a href="users.php" class="btn btn-warning btn-user btn-block" style="background-color: #2658a8; border-color: #2658a8;">Return to Users</a>
</form>

2 个答案:

答案 0 :(得分:2)

您的代码中有一些需要注意的地方。

关于第1点的旁注,请参见下面的“其他说明”。

1)@echo off set source="C:dir" set target="C:dir2" FOR /F "delims=" %%I IN ('DIR %source%\*.* /A:-D /O:-D /B') DO COPY %source%\"%%I" %target% & gpg --encrypt --recipient CCB779A942CEB9A0 --output \"%%I" %target% & echo %%I & GOTO :END :END TIMEOUT 30 <您没有对该变量执行任何操作,它们只是变量声明。您可以做的是在要回显该变量的页面上回显该变量,并在其后添加TO_CHAR,以使其停止执行。

2)SELECT * FROM USER_GROUP WHERE TO_CHAR(ID) IN (SELECT CONCAT(CONCAT('(',REPLACE(LTRIM(RTRIM(REPLACE(COLUMNA, ',', ' '))), ' ', ',')),')') FROM Table1) 是mysqli_函数。您不能将其与PDO混合使用,可以将$msgexit;num_rows一起使用。

或使用rowCount()

fetchColumn()

3)在每个标题后添加一个if ($stmt->rowCount() > 0){...}。否则,您的代码可能想继续进行下去。

注意:由于您使用的是标题重定向,请确保您没有在标题之前输出,否则它将失败。

其他说明:

使用fetchColumn()可能不是一个好主意,因为这可能会默默地和过早地失败。我将“不”设为条件语句,然后检查是否存在一行并从那里处理错误。

此外,您在表单中的$if_row = $stmt->fetchColumn(); if ($if_row > 0) { $msg = "A record exists."; } 可能会引发未定义的可变消息。您可以使用ternary operator或标准exit;

例如:

if ($stmt = $pdo->prepare....){...}

答案 1 :(得分:0)

仅在发生验证错误时设置变量$msg。这不会阻止您的代码尝试执行数据库操作。也许如果包含的if语句在运行数据库操作之前检查了$msg是否为空。

if (empty($msg) && $stmt = $pdo->prepare('SELECT id, password FROM users WHERE username = ?')) {

相关问题