【问题标题】:Is there a way to add priority to a php echo message?有没有办法为 php echo 消息添加优先级?
【发布时间】:2021-06-04 10:09:02
【问题描述】:

这是 jslogin.php

<?php
error_reporting(-1);
session_start();
require_once('config.php');


$email = $_POST['email'];
$username = $_POST['username'];
$password = $_POST['password'];

$isValid = true;
if (empty($password)) {
    echo 'You need to enter a Password';
    $isValid = false;
}

if (empty($username)) {
    echo 'You need to enter a Username';
    $isValid = false;
}

if (empty($email)) {
    echo 'You need to enter a Email Address';
    $isValid = false;
}elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo "You need to have a valid Email Address";
    $isValid = false;
}

if ($isValid) {
    $sql = "SELECT * FROM accounts WHERE username=? and password=? and email=? LIMIT 1";
    $stmtselect = $db->prepare($sql);
    $result = $stmtselect->execute([$username, $password, $email]);
    $user = $stmtselect->fetch(PDO::FETCH_ASSOC);
    if ($stmtselect->rowCount() > 0) {
        $_SESSION['accounts'] = $user;
        echo 'You have signed in successfully!';
    } else {
        echo 'Incorrect Username or Password or Email';
    }
}

这是 login.php

<?php 
error_reporting(-1);
    session_start();
    
if(isset($_SESSION['hello_world_accounts'])){
    header("Location: index.php");
}

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <title>Programming Knowledge Login</title>
    <link rel="stylesheet" type="text/css" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.1/css/all.css" integrity="sha384-50oBUHEmvpQ+1lW4y57PTFmhCaXp0ML5d60M1M7uH2+nqUivzIebhndOJK28anvf" crossorigin="anonymous">
    <link rel="stylesheet" type="text/css" href="css/styles.css">
</head>
<body>
<div class="container h-100">
    <div class="d-flex justify-content-center h-100">
        <div class="user_card">
            <div class="d-flex justify-content-center">
                <div class="brand_logo_container">
                    <img src="img/logo.png" class="brand_logo" alt="Programming Knowledge logo">
                </div>
            </div>  
            <div class="d-flex justify-content-center form_container">
                <form method="post">
                    <div class="input-group mb-2">
                        <div class="input-group-append">
                            <span class="input-group-text"><em class="fas fa-user"></em></span>                 
                        </div>
                        <input type="text" name="username" id="username" class="form-control input_user" placeholder="Username" required>
                    </div>
                    <div class="input-group mb-2">
                        <div class="input-group-append">
                            <span class="input-group-text"><em class="fas fa-key"></em></span>                  
                        </div>
                        <input type="password" name="password" id="password" class="form-control input_pass" placeholder="Password" required>
                    </div>
                    <div class="input-group mb-1">
                        <div class="input-group-append">
                            <span class="input-group-text"><em class="fas fa-inbox"></em></span>                    
                        </div>
                        <input type="email" name="email" id="email" class="form-control input_pass" placeholder="Email" required>
                    </div>
                    <div class="form-group">
                        <div class="custom-control custom-checkbox">
                            <input type="checkbox" name="rememberme" class="custom-control-input" id="customControlInline">
                            <label class="custom-control-label" for="customControlInline">Remember me</label>
                        </div>
                    </div>
                
            </div>
            <div class="d-flex justify-content-center mt-1 login_container">
                <button type="button" name="button" id="login" class="btn login_btn">Login</button> 
            </div>
            </form>
            <div class="mt-3 mb-1">
                <div class="d-flex justify-content-center links">
                    Don't have an account? <a href="registration.php" class="ml-2">Sign Up</a>
                </div>
                <div class="d-flex justify-content-center">
                    <a href="#">Forgot your password?</a>
                </div>
            </div>
        </div>
    </div>
</div>
<script src="http://code.jquery.com/jquery-3.3.1.min.js"
              integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
              crossorigin="anonymous"></script>
<script type="text/javascript" src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<script>
    $(function(){
        $('#login').click(function(e){

            var valid = this.form.checkValidity();

            if(valid){
                var username = $('#username').val();
                var password = $('#password').val();
                var email = $('#email').val();
            }

            e.preventDefault();

            $.ajax({
                type: 'POST',
                url: 'jslogin.php',
                data:  {username: username, password: password, email: email},
                success: function(data){
                    alert(data);
                    if($.trim(data) === "1"){
                        setTimeout(' window.location.href =  "index.php"', 1000);
                    }
                },
                error: function(data){
                    alert('There were errors while doing the operation.');
                }
            });

        });
    });
</script>
</body>
</html>

这是 config.php

<?php

error_reporting(-1);
$db_user = "root";
$db_pass = "";
$db_name = "hello_world_accounts";

$db = new PDO('mysql:host=localhost;dbname='. $db_name . ';charset=utf8', $db_user, $db_pass);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

这是 index.php

<?php 

error_reporting(-1);
session_start();

    if(!isset($_SESSION['hello_world_accounts'])){
        header("Location: login.php");
    }

    if(isset($_GET['logout'])){
        session_destroy();
        unset($_SESSION);
        header("Location: login.php");
    }

?>
<!DOCTYPE>
<html lang="en">
<head>
<title>Welcome</title>
</head>
<body>
<p>Welcome to index</p>


<a href="index.php?logout=true">Logout</a>
</body>
</html>

每次我输入我的电子邮件而不是我的用户名和密码时,它都会说我需要把三个都输入,即使一个已经输入了 为什么会发生这种情况,我该如何解决? 我考虑过优先事项,但我不知道该怎么做或做什么......

页面其余代码如下

请不要说密码是纯文本。

这是我的测试mysql。 My Test MYSQL 这是我的测试网站。 My Test Website

【问题讨论】:

  • !stripos 不正确。应该是!== FALSE 那也不是应该如何验证电子邮件地址
  • 您有很多不必要的嵌套 if/else。我建议将所有内容更改为 else if
  • @user3783243 我试过了! == FALSE 说有一个错误,什么都行不通。我做了 !stripos 并且我的消息正在显示。如果它等于'',当我这样做时它开始出错
  • 另一个改进点:使用当前结构,即使有多个错误,您也只会向用户显示一个错误。这样,在更正错误并再次提交后,用户将看到下一个错误,然后重复该过程……作为用户,我希望有一个表单可以一次告诉我所有错误。考虑发送一组错误消息。
  • 请不要使用error_reporting(0);开发,你从一开始就是在自找麻烦。在生产阶段,情况就不同了,但在开发阶段从来没有。

标签: php if-statement echo


【解决方案1】:

这是您通过格式化程序运行时的原始代码。您应该注意到,正如人们所指出的那样,它像疯了一样缩进并且有很多嵌套。即使数据无效,您也会在每个请求上查询数据库。

$username = $_POST['username'];
$password = $_POST['password'];
$email = $_POST['email'];
$valid = "You need to have a valid Email Address";

$sql = "SELECT * FROM accounts WHERE username=? and password=? and email=? LIMIT 1";
$stmtselect  = $db->prepare($sql);
$result = $stmtselect->execute([$username, $password, $email]);

if (stripos($password, '')) {
    echo 'You need to enter a Password';
} else {
    if (stripos($username, '')) {
        echo 'You need to enter a Username';
    } else {
        if (stripos($email, '')) {
            echo 'You need to enter a Email Address';
        } else {
            if (!stripos($email, '@')) {
                echo $valid;
            } else {
                if (!stripos($email, '.')) {
                    echo $valid;
                } else {
                    if (!stripos($email, 'com')) {
                        echo $valid;
                    } else {
                        if ($result) {
                            $user = $stmtselect->fetch(PDO::FETCH_ASSOC);
                            if ($stmtselect->rowCount() > 0) {
                                $_SESSION['accounts'] = $user;
                                echo 'You have signed in successfully!';
                            } else {
                                echo 'Incorrect Username or Password or Email';
                            }
                        } else {
                            echo 'There were errors while connecting to database.';
                        }
                    }
                }
            }
        }
    }
}

相反,这里是清理它的快速尝试。主要变化是切换到empty() 检查、使用elseif、更好的电子邮件地址验证器以及将查询移至最后的else 子句。

$username = $_POST['username'];
$password = $_POST['password'];
$email = $_POST['email'];

if (empty($password)) {
    echo 'You need to enter a Password';
} elseif (empty($username)) {
    echo 'You need to enter a Username';
} elseif (empty($email)) {
    echo 'You need to enter a Email Address';
} elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo "You need to have a valid Email Address";
} else {
    $sql = "SELECT * FROM accounts WHERE username=? and password=? and email=? LIMIT 1";
    $stmtselect = $db->prepare($sql);
    $result = $stmtselect->execute([$username, $password, $email]);
    $user = $stmtselect->fetch(PDO::FETCH_ASSOC);
    if ($stmtselect->rowCount() > 0) {
        $_SESSION['accounts'] = $user;
        echo 'You have signed in successfully!';
    } else {
        echo 'Incorrect Username or Password or Email';
    }
}

编辑

如果您的意图是显示多条错误消息,而不是仅仅停留在第一个错误消息(就像您的原始代码那样),那么您可以使用多个 if 块。大多数人会将错误消息收集到一个数组中,但我会留给你。

$isValid = true;
if (empty($password)) {
    echo 'You need to enter a Password';
    $isValid = false;
}

if (empty($username)) {
    echo 'You need to enter a Username';
    $isValid = false;
}

if (empty($email)) {
    echo 'You need to enter a Email Address';
    $isValid = false;
}elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo "You need to have a valid Email Address";
    $isValid = false;
}

if ($isValid) {
    $sql = "SELECT * FROM accounts WHERE username=? and password=? and email=? LIMIT 1";
    $stmtselect = $db->prepare($sql);
    $result = $stmtselect->execute([$username, $password, $email]);
    $user = $stmtselect->fetch(PDO::FETCH_ASSOC);
    if ($stmtselect->rowCount() > 0) {
        $_SESSION['accounts'] = $user;
        echo 'You have signed in successfully!';
    } else {
        echo 'Incorrect Username or Password or Email';
    }
}

编辑

如果您没有在&lt;form&gt; it defaults to GET 上提供method。但是,您的代码期望它是 POST。将表单更改为&lt;form method="post"&gt;

编辑

我不会使用您的任何 HTML,而是会创建一个非常简单的表单,它可以 POST 给自己。这是您在使用任何 Web 语言进行编程时学习的非常常见的第​​一个任务。这个页面本身,忽略你的数据库、样式和 JS 逻辑应该 100% 自己工作。一旦你证明你可以开始使用会话增强它,然后也许是 AJAX。但从简单开始。

该表单不包含required 等常规设置或字段上的最佳类型,因为我只是试图使其尽可能简单。

我确实添加了 errors 数组,这消除了对 $isValid 的需要,因为我们现在可以检查错误中是否包含任何内容。

请自行尝试这段代码,一旦你了解它的工作原理,然后开始修改它,如果你真的需要,可能会在这里提出新问题。

<?php

$errors = false;

$email = '';
$username = '';
$password = '';

if ('POST' === $_SERVER['REQUEST_METHOD']) {
    $email = $_POST['email'];
    $username = $_POST['username'];
    $password = $_POST['password'];

    $errors = [];

    if (empty($password)) {
        $errors[] = 'You need to enter a Password';
    }

    if (empty($username)) {
        $errors[] = 'You need to enter a Username';
    }

    if (empty($email)) {
        $errors[] = 'You need to enter a Email Address';
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $errors[] = "You need to have a valid Email Address";
    }
}

if ($errors) {
    echo '<pre>';
    echo implode(PHP_EOL, $errors);
    echo '</pre>';
}
?>
<form method="post">
    <label>Email <input type="text" name="email" value="<?php echo htmlspecialchars($email); ?>"/></label><br/>
    <label>Username <input type="text" name="username" value="<?php echo htmlspecialchars($username); ?>"></label><br/>
    <label>Password <input type="password" name="password"></label><br/>
    <input type="submit" value="Submit">
</form>

【讨论】:

  • 何时执行此操作同样的问题。
  • 这是一个在线快速演示,显示正在设置密码,仅此而已。错误消息是“您需要输入用户名”:3v4l.org/QHb9C
  • 当我去那里时,如果我把奶酪作为密码,它说我需要密码而不是用户名或电子邮件
  • 过滤器验证电子邮件不起作用
  • 我已经更新了上面的示例,以包括独立验证四个项目的多项检查。这是一个用于测试的在线版本,它也显示了电子邮件部分的工作。 3v4l.org/dJf2b 如果您的电子邮件地址不适用于该测试,请发布。 SMTP 地址有很多边缘情况,但在野外很少见。
猜你喜欢
  • 2019-08-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-11
  • 2012-04-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多