Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/276.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP检查字符串是否在3到20个字符之间_Php - Fatal编程技术网

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

PHP检查字符串是否在3到20个字符之间,php,Php,我正在为php做一个用户名检查,我需要检查字符串是否在3到20个字符之间,我已经尝试过了,但它不起作用! 这是我的代码示例的链接,我不知道如何使用stackoverflow:( if(isset($\u POST['submit'])){ $user=trim(mysql\u real\u escape\u字符串($\u POST['user']); $email=trim(mysql\u real\u escape\u string($\u POST['email']); $pass1=tri

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

if(isset($\u POST['submit'])){
$user=trim(mysql\u real\u escape\u字符串($\u POST['user']);
$email=trim(mysql\u real\u escape\u string($\u POST['email']);
$pass1=trim(mysql\u real\u escape\u字符串($\u POST['pass1']);
$pass2=trim(mysql\u real\u escape\u字符串($\u POST['pass2']);
如果(!empty($user)&&!empty($email)&&!empty($pass1)&&!empty($pass2)){
if(ctype_alnum($user)){
if(过滤变量($email,过滤验证电子邮件)){
if(strlen($user)<3){
如果(strlen($user)>20){
$query1=mysql_query(“从用户名为“$user”的用户中选择用户名”);
$query2=mysql_query(“选择来自用户的电子邮件,其中电子邮件=“$email”);
$count1=mysql\u num\u行($query1);
$count2=mysql\u num\u行($query2);
如果($count1==0&&$count2==0){
如果($pass1==$pass2){
}否则{
$output='错误,密码不匹配!';
}
}否则{
$output='错误、用户名和电子邮件被占用!';
}
如果($count1==1){
$output='错误,用户名被占用!';
}
如果($count2==1){
$output='错误,已接收电子邮件!';
}
}否则{
$output='CC错误,用户名必须为3-20个字符!';
}
}否则{
$output='xx错误,用户名必须为3-20个字符!';
}
}否则{
$output='错误,无效电子邮件!';
}
}否则{
$output='错误,用户名必须是字母数字!';
}
}否则{
$output='错误,缺少字段!';
}
}

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

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

if(strlen($user)>=3&&strlen($user)标准MYSQL已弃用,不应再使用。如果您在服务器上升级PHP版本,您将遇到一些麻烦

您应该查看MYSQLI prepared语句或PDO。prepared语句比标准查询安全得多,并自动处理转义字符串等问题

我还将研究如何使用try/catch语句。try/catch语句允许您生成错误消息,而无需构建一个庞大的if语句层,这样可以节省资源和时间。它也更容易看到

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

最好只访问和使用数据库的次数尽可能少。通过一个查询而不是两个查询可以提取电子邮件和用户名。然后通过数据循环进行检查。这可以节省数据库活动和资源

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

# 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>";

}
#启动try/catch语句检查抛出的异常(错误消息)
试一试{
#检查$\u POST以启动脚本
如果(!空($\u POST)){
#循环遍历每个post值
foreach($\发布为$key=>$val){
#检查每个post值是否为空,并抛出和异常,如果不是,则将其设置为变量
如果(!空($val)){
${$key}=trim($val);
}
否则{
#抛出异常(错误消息)
抛出新异常(“错误,缺少字段”);
}
}
#检查$user是否为字母数字且至少包含3到20个字符(原始问题的答案!!!)
如果(!ctype_alnum($user)| strlen($user)<3 | strlen($user)>20){
#抛出异常(错误消息)
抛出新异常(“错误,用户名必须是字母数字,并且至少有3到20个字符。”);
}
#检查$email是否有效
if(过滤变量($email,过滤验证电子邮件)){
#抛出异常(错误消息)
抛出新异常(“错误,无效电子邮件”);
}
#检查$pass1和$pass2的值是否相同
如果($pass1!=$pass2){
#抛出异常(错误消息)
抛出新异常(“错误,密码不匹配。”);
}
#建立MYSQLI连接
$mysqli=newmysqli($servername、$username、$password、$dbname);
如果($mysqli->connect\u errno){
#抛出连接错误消息
抛出新异常(“错误,无法连接到数据库。”);
}
#准备要执行的查询
$stmt=$mysqli->prepare(“选择`username`、`email`FROM`users`WHERE`username`=?或`email`=?”;
#将这两个参数绑定到语句中
$stmt->bind_参数(“ss”、$user、$email);
如果($stmt==false){
#抛出异常(错误消息)
抛出新异常(“错误,无法处理提交的数据”);
}
#超越你的疑问
$stmt->execute();
如果($stmt==false){
#抛出异常(错误消息)
抛出新异常(“错误,计数不执行数据库查询”);
}
#绑上绳子
# 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>";

}