PHP验证总是显示错误消息

3

我在使用PHP进行服务器端验证时遇到了问题。问题是,即使输入的值是有效的,它仍然显示验证错误消息。例如,在用户名字段上,如果我输入不包含特殊符号的内容,它仍然进入if语句并显示错误消息:“用户名不能包含特殊字符”。正则表达式似乎工作正常,所以我认为这是一个逻辑错误。以下是我的PHP代码:

<?php

/**
 * Include our MySQL connection.
 */
require 'connect.php';

$error = '';
try {
//If the POST var "register" exists (our submit button), then we can
//assume that the user has submitted the registration form.
    if (isset($_POST['register'])) {

        $form = $_POST;
        $username = $form['username'];
        $password = $form['password'];
        $firstName = $form['firstName'];
        $lastName = $form['lastName'];
        $address = $form['address'];
        $email = $form['email'];
        $age = $form['age'];
        $phone = $form['phone'];
//Retrieve the field values from our registration form.
        $username = !empty($_POST['username']) ? trim($_POST['username']) : null;
        $password = !empty($_POST['password']) ? trim($_POST['password']) : null;

//TO ADD: Error checking (username characters, password length, etc).
//Basically, you will need to add your own error checking BEFORE
//the prepared statement is built and executed.
        //Validations username
        if (strlen($username) < 4 || strlen($username) > 8 || empty($username)) {
            throw new Exception("User name must be between 4 an 8 symbols.");
        }

        $patern = '[A-Za-z0-9]+';
        if (!preg_match($patern, $form['username'])) {
            throw new Exception("User name must not contains Special characters.");
        }
        $patern = '^(([^<>()\[\]\.,;:\s@\"]+(\.[^<>()\[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$';
        //Validation email
        if (!preg_match($patern, $email)) {
            throw new Exception("Please fill valid email.");
        }
        //Validation password
        if (strlen($password < 8 || strlen($password > 15) || empty($password))) {
            throw new Exception("Password must be between 8 an 15 symbols.");
        }
        $patern = '(?=(.*\d){2,})(?=.*[A-Z]{1,})(?=.*[a-zA-Z]{2,})(?=.*[!@~#$%^&?]{1,})[0-9a-zA-Z!@~#?$^%&`]{8,15}';
        if (!preg_match($patern, $password)) {
            throw new Exception("Password must contains at least 1 special symbol at least 1 uppercase letter at least 2 numbers at least 3 letters.");
        }
        if (strlen($password < 8 || strlen($password > 15) || empty($password))) {
            throw new Exception("Password must contains at least 1 special symbol at least 1 uppercase letter at least 2 numbers at least 3 letters.");
        }
        if (strlen($phone) != 10) {
            throw new Exception("Phone must be 10 numbers.");
        }
//Now, we need to check if the supplied username already exists.

//Construct the SQL statement and prepare it.
        $sql = "SELECT COUNT(username) AS num FROM users WHERE username = :username";
        $stmt = $pdo->prepare($sql);

//Bind the provided username to our prepared statement.
        $stmt->bindValue(':username', $username);

//Execute.
        $stmt->execute();

//Fetch the row.
        $row = $stmt->fetch(PDO::FETCH_ASSOC);

//If the provided username already exists - display error.
//TO ADD - Your own method of handling this error. For example purposes,
//I'm just going to kill the script completely, as error handling is outside
//the scope of this tutorial.
        if ($row['num'] > 0) {
            throw new Exception('That username already exists!');
        }
        $sql = "SELECT COUNT(email) AS test FROM users WHERE email = :email";
        $stmt = $pdo->prepare($sql);

//Bind the provided username to our prepared statement.
        $stmt->bindValue(':email', $email);

//Execute.
        $stmt->execute();

//Fetch the row.
        $result = $stmt->fetch(PDO::FETCH_ASSOC);

//If the provided username already exists - display error.
//TO ADD - Your own method of handling this error. For example purposes,
//I'm just going to kill the script completely, as error handling is outside
//the scope of this tutorial.
        if ($result['test'] > 0) {
            throw new Exception('That email already exists!');
        }
//Hash the password as we do NOT want to store our passwords in plain text.
        $passwordHash = password_hash($password, PASSWORD_BCRYPT, array("cost" => 12));

//Prepare our INSERT statement.
//Remember: We are inserting a new row into our users table.
        $sql = "INSERT INTO users (username, password, email, phone, address, first_name, last_name, age) 
VALUES (:username, :password,:email, :phone, :address, :first_name, :last_name, :age)";
        $stmt = $pdo->prepare($sql);

//Bind our variables.
        $stmt->bindValue(':username', $username);
        $stmt->bindValue(':password', $passwordHash);
        $stmt->bindValue(':email', $email);
        $stmt->bindValue(':phone', $phone);
        $stmt->bindValue(':address', $address);
        $stmt->bindValue(':first_name', $firstName);
        $stmt->bindValue(':last_name', $lastName);
        $stmt->bindValue(':age', $age);

//Execute the statement and insert the new account.
        $result = $stmt->execute();

//If the signup process is successful.
        if ($result) {
            $_SESSION['username'] = $firstName;

            header('Location: login.php');

        }

    }
} catch (Exception $exception) {
    $error = $exception->getMessage();
}
?>

还有HTML表单:

<form name="registration" action="#" method="post">
            <fieldset>
                <legend class="extraPlace">Register</legend>
                <?php if ($error) : ?>
                    <h2 style="color:red">   <?= $error ?></h2>
                <?php endif; ?>
                <?php $error = ''; ?>
                <div class="input-group margin col-lg-6">
                    <span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
                    <input class="form-control" id="username" name="username" type="text" placeholder="Username *"
                           minlength="4" maxlength="8" min="4" required>

                </div>

                <div class="input-group margin">
                    <span class="input-group-addon"><i class="glyphicon glyphicon-lock"></i></span>
                    <input class="form-control" id="password" name="password" type="password" placeholder="Password *"
                           maxlength="15" minlength="8" required>

                    <span class="input-group-addon"><i class="glyphicon glyphicon-lock"></i></span>
                    <input class="form-control" id="confirm_password" name="confirmPass" type="password"
                           placeholder="Confirm Password *" required>

                </div>

                <div class="input-group margin">
                    <span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
                    <input class="form-control" id="firstName" name="firstName" type="text" placeholder="First Name *"
                           required>

                    <span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
                    <input class="form-control" id="lastName" name="lastName" type="text" placeholder="Last Name *"
                           required>
                </div>

                <div class="input-group margin col-lg-6">
                    <span class="input-group-addon"><i class="glyphicon glyphicon-envelope"></i></span>
                    <input class="form-control" id="email" name="email" type="email" placeholder="Email *" required>
                </div>

                <div class="input-group margin col-lg-6">
                    <span class="input-group-addon"><i class="glyphicon glyphicon-phone-alt"></i></span>
                    <input class="form-control" id="phone" name="phone" type="number" maxlength="10"
                           placeholder="Phone Number *" required>
                </div>

                <div class="input-group margin col-lg-6">
                    <span class="input-group-addon"><i class="glyphicon glyphicon-home"></i></span>
                    <input class="form-control" id="address" name="address" type="text" placeholder="Address *"
                           required>
                </div>

                <div class="input-group margin col-lg-6">
                    <span class="input-group-addon"><i class="glyphicon glyphicon-time"></i></span>
                    <input class="form-control" id="age" name="age" type="number" placeholder="Age *" min="18" required>
                </div>

                <div class="checkbox alignLeftContent">
                    <label>
                        <input type="checkbox" name="agreement" value="1" required> I have read and agree to the <a
                                href="https://www.un.org/Depts/ptd/terms-and-conditions-agreement">Terms and Conditions
                            *</a>
                    </label><br>
                    <label>
                        <input type="checkbox" name="gdpr" value="1" required> GDPR Agreement *
                    </label>
                    <div class="margin"><span>* &nbsp;&nbsp; Mandatory fields</span></div>
                </div>

                <button class="btn btn-success " type="submit" name="register">Register</button>
            </fieldset>
        </form>

$patern = '/[A-Za-z0-9]+/'; - Karlo Kokkak
已经修改了,但仍然是一样的。 - TwinAxe96
1
$patern = '/[A-Za-z0-9]+/'; - Karlo Kokkak
你如何调用服务器端脚本?你使用GET还是POST方法? - floverdevel
哦,抱歉,我刚刚发现它是POST请求。问题肯定出在别的地方了... :) - floverdevel
我在模式的开头和结尾缺少了一个 '#',显然这是 PHP 所必需的。 - TwinAxe96
2个回答

5

问题出在你的正则表达式上:

$patern = '[A-Za-z0-9]';

您缺少分隔符,应将模式修复到开头和结尾,因为现在如果字符串仅包含无效字符,则只会失败。
$patern = '#^[A-Za-z0-9]+$#';
                          ^ delimiter
                         ^ end of string
                        ^ 1 or more characters
            ^ beginning of string
           ^ delimiter

或者您可以通过反转字符组来搜索无效字符:

$patern = '#[^A-Za-z0-9]#';
//           ^ negate the character class
// or case insensitive
$patern = '#[^a-z0-9]#i';

// Change the condition
if (preg_match($patern, $form['username'])) {
    // At least 1 invalid character found

这解决了问题,但为什么要在开头和结尾加上定界符“#”? - TwinAxe96
@TwinAxe96 这在 preg_* 中是必需的,请参见 http://php.net/manual/en/regexp.reference.delimiters.php - jeroen

0
$patern = '#[^a-z0-9]#i';

        if (preg_match($patern, $form['username'])) {
            throw new Exception("User name must not contains Special characters.");
        }

只需替换此块


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接