PHP检查字符串是否在3到20个字符之间

时间:2017-03-23 00:02:28

标签: php

我正在检查php的用户名,我需要检查字符串是否在3到20个字符之间,我试过这个,但它不起作用! 继承我的代码示例的链接,我不知道如何工作stackoverflow :(

if(isset($_POST['submit'])){
        $user = trim(mysql_real_escape_string($_POST['user']));
        $email = trim(mysql_real_escape_string($_POST['email']));
        $pass1 = trim(mysql_real_escape_string($_POST['pass1']));
        $pass2 = trim(mysql_real_escape_string($_POST['pass2']));
        if(!empty($user) && !empty($email) && !empty($pass1) && !empty($pass2)){
            if(ctype_alnum($user)){
                if(filter_var($email, FILTER_VALIDATE_EMAIL)){
                    if(strlen($user) < 3){
                        if(strlen($user) > 20){
                            $query1 = mysql_query("SELECT username FROM users WHERE username='$user'");
                            $query2 = mysql_query("SELECT email FROM users WHERE email='$email'");
                            $count1 = mysql_num_rows($query1);
                            $count2 = mysql_num_rows($query2);
                            if($count1 == 0 && $count2 == 0){
                                if($pass1 == $pass2){

                                } else {
                                    $output = '<div id="output"><header><h1>Error, passwords do not match!</h1><a href="#" onclick="document.getElementById(\'output\').style.display = \'none\';return false;"><i class="fa fa-times"></i></a></header></div>';
                                }
                            } else {
                                $output = '<div id="output"><header><h1>Error, username & email are taken!</h1><a href="#" onclick="document.getElementById(\'output\').style.display = \'none\';return false;"><i class="fa fa-times"></i></a></header></div>';
                            }
                            if($count1 == 1){
                                $output = '<div id="output"><header><h1>Error, username is taken!</h1><a href="#" onclick="document.getElementById(\'output\').style.display = \'none\';return false;"><i class="fa fa-times"></i></a></header></div>';
                            }
                            if($count2 == 1){
                                $output = '<div id="output"><header><h1>Error, email is taken!</h1><a href="#" onclick="document.getElementById(\'output\').style.display = \'none\';return false;"><i class="fa fa-times"></i></a></header></div>';
                            }
                        } else {
                            $output = '<div id="output"><header><h1> CC Error, username must be 3-20 characters!</h1><a href="#" onclick="document.getElementById(\'output\').style.display = \'none\';return false;"><i class="fa fa-times"></i></a></header></div>';
                        }
                    } else {
                        $output = '<div id="output"><header><h1>xx Error, username must be 3-20 characters!</h1><a href="#" onclick="document.getElementById(\'output\').style.display = \'none\';return false;"><i class="fa fa-times"></i></a></header></div>';
                    }
                } else {
                    $output = '<div id="output"><header><h1>Error, invalid email!</h1><a href="#" onclick="document.getElementById(\'output\').style.display = \'none\';return false;"><i class="fa fa-times"></i></a></header></div>';
                }
            } else {
                $output = '<div id="output"><header><h1>Error, username must be alphanumeric!</h1><a href="#" onclick="document.getElementById(\'output\').style.display = \'none\';return false;"><i class="fa fa-times"></i></a></header></div>';
            }
        } else {
            $output = '<div id="output"><header><h1>Error, missing fields!</h1><a href="#" onclick="document.getElementById(\'output\').style.display = \'none\';return false;"><i class="fa fa-times"></i></a></header></div>';
        }
    }

2 个答案:

答案 0 :(得分:0)

如果只对$ user进行一次检查:

if (strlen($user) >= 3 && strlen($user) <= 20) {
    ...
}

答案 1 :(得分:0)

不推荐使用标准MYSQL,不应再使用它。如果您在服务器上升级了PHP版本,则会遇到麻烦。

您应该查看MYSQLI预处理语句或PDO。准备好的语句比标准查询更安全,并自动处理转义字符串等问题。

我还会研究使用try / catch语句。 Try / catch语句允许您生成错误消息,而无需构建可以节省资源和时间的巨大if语句层。它的眼睛也更容易。

此外,我建议在打开连接或访问数据库之前,根据您的帖子值进行所有检查。最好不要在必要时访问或使用数据库。

最好只以尽可能少的时间访问和使用数据库。拉动电子邮件和用户名可以使用一个查询而不是两个查询来完成。然后遍历您的数据以进行检查。这节省了数据库活动和资源。

我在下面使用您提交的代码提供了一个示例,其中还包含原始问题的答案。

# Start your try/catch statement to check for thrown exceptions (error messages)
try {

    # Check for $_POST to initiate script
    if( !empty($_POST) ){

        # Loop through each post value
        foreach( $_POST as $key => $val ){

            # Check if each post value is empty and throw and exception and if not set it as a variable
            if( !empty($val) ){

                ${$key} = trim($val);

            }

            else {

                # Throw Exception (error message)
                throw new Exception("Error, missing fields.");

            }

        }

        # Check if $user is alphanumeric and is at least 3 to 20 characters (THE ANSWER TO YOUR ORIGINAL QUESTION!!!)
        if( !ctype_alnum($user) || strlen($user) < 3 || strlen($user) > 20 ){

            # Throw Exception (error message)
            throw new Exception("Error, username must be alphanumeric and at least 3 to 20 characters.");

        }

        # Check if $email is valid
        if( filter_var($email, FILTER_VALIDATE_EMAIL) ){

            # Throw Exception (error message)
            throw new Exception("Error, invalid email.");

        }

        # Check if $pass1 and $pass2 are the same value
        if( $pass1 != $pass2 ){

            # Throw Exception (error message)
            throw new Exception("Error, passwords do not match.");

        }

        # Make MYSQLI Connection
        $mysqli = new mysqli($servername, $username, $password, $dbname);

        if ( $mysqli->connect_errno ) {

            # Throw connections error message
            throw new Exception("Error, could not connect to database.");

        }

        # Prepare your query for execution
        $stmt = $mysqli->prepare("SELECT `username`,`email` FROM `users` WHERE `username` = ? OR `email` = ?");

        # Bind the two parameters to your statement
        $stmt->bind_param("ss", $user, $email);

        if ( $stmt === false ) {

            # Throw Exception (error message)
            throw new Exception("Error, could not process data submitted.");

        }

        # Excecute your query
        $stmt->execute();

        if ( $stmt === false ) {

            # Throw Exception (error message)
            throw new Exception("Error, count not execute database query.");

        }

        # Bind the results to a variable
        $stmt->bind_result($users);

        # Fetch your data from results
        while($stmt->fetch()){

            $foundusers = $users;

        }

        if ( $stmt === false ) {

            # Throw Exception (error message)
            throw new Exception("Error, could not get results from database.");

        }

        # Set counters for username and emails found
        $usernames = 0;
        $emails = 0;

        # Loop through each database entry retrieved and check for matching usernames and emails
        foreach( $foundusers as $thisuser ){

            if( !empty($thisuser["email"]) && $thisuser["email"] == $email ){

                # Add 1 to the $emails counter
                $emails++;

            }

            if( !empty($thisuser["username"]) && $thisuser["username"] == $user ){

                # Add 1 to the $usernames counter
                $usernames++;

            }

        }

        # close your statement
        $stmt->close();

        #Check if matching usernames OR emails were found
        if( $usernames > 0 || $emails > 0 ){

            # Check if $usernames and $emails counter is great than 0
            if( $usernames >= 1 && $emails >= 1 ){

                # Throw Exception (error message)
                throw new Exception("Error, username & email are taken.");

            }

            # Check if $usernames counter is great than 0
            if( $usernames >= 1 ) {

                # Throw Exception (error message)
                throw new Exception("Error, username is taken.");

            }

            # Check if $emails counter is great than 0
            if( $emails >= 1 ) {

                # Throw Exception (error message)
                throw new Exception("Error, email is taken.");

            }

        }

    }
    else {

        # Throw Exception (error message)
        throw new Exception("Error, could not initiate script.");

    }

    # Report no usernames were found (only shows if no exceptions are thrown prior to this code)
    $output = "<div onclick=\"this.style.display = 'none'\"><header><h1>Success, username & email are available.</h1><a href='#'><i class='fa fa-times'></i></a></header></div>";

}

# Catch any exceptions thrown and output the error
catch( Exception $e ) {

    # Check if statement is still open and close it
    if($stmt){
        $stmt->close();
    }

    # Create your error response
    $output = "<div onclick=\"this.style.display = 'none'\"><header><h1>" . $e->getMessage() . "</h1><a href='#'><i class='fa fa-times'></i></a></header></div>";

}