在php中向用户显示错误消息的正确方式是什么


What is a proper way of displaying error messages to a user in php?

我有一个简单的登录系统,但当他们没有正确键入凭据时,我希望能够将消息放在<p></p>或类似的文件中,而不是回显错误消息。我尝试使用空数组

$data = array();

然后在出现错误时设置状态变量,而不是使用回波

$data["status"] = "...."

在html部分,我放入

<?php if ( isset($status) ) : ?>
    <p><?= $status; ?></p>
<?php endif; ?>

但我似乎无法让它工作。我也试过:

extract($data)

但我显然又做错了什么。我不确定这是否是正确的方式。使用javascript或jquery会是更好的处理方式吗?不管怎样,这是我的密码。

$conn = DBconnect($config);
//create and empty array so we can ifor the users.
$data = array();
// if the user has submitted the form
if( $_SERVER["REQUEST_METHOD"] === "POST") {
    //protect the posted value then store them to variables
    $username = protect($_POST["username"]);
    $password = protect($_POST["password"]);
    //Check if the username or password boxes were not filled in
    if ( !$username || !$password ){
        // if not display an error message.
        $data["status"] =  "You need to fill in a username and password!";
    }else{
        //check if the username and password match.
        $stmt = query("SELECT * FROM users WHERE username = :username AND password = :password",
                        array("username" => $username, "password" => $password),
                        $conn);
        $row = $stmt->fetch(PDO::FETCH_ASSOC);
        if(!$row){
            //display an error message
            $data["status"] =  "Username or Password is incorrect.";
        }elseif($row["active"] !=1) {
            $data["status"] =  "You have not activated your account!";
            }else{
                //we log the user in.

这种情况还在继续。这是html部分

<div class="container">
  <form class="form-signin" action ="" method = "post">
    <h2 class="form-signin-heading">Please Log In</h2>
    <input type="text" class="input-block-level" name = "username" id = "username" placeholder="Username">
    <input type="password" class="input-block-level" name = "password" id = "password" placeholder="Password">
    <label class="checkbox">
      <input type="checkbox" value="remember-me"> Remember me
    </label>
     <input type="submit" class = "btn btn-large btn-primary" name = "submit" value="Log in!" >
    <?php if ( isset($status) ) : ?>
      <p><?= $status; ?></p>
    <?php endif; ?>
  </form>
</div> <!-- /container -->
$data["status"] = "...."
and on the html part i put in
<?php if ( isset($status) ) : ?>
    <p><?= $status; ?></p>
<?php endif; ?>

就我所见,$status尚未设置。设置CCD_ 3。

至于传递错误消息的正确方法,如评论中所建议的;因为这个错误是一个只有在当前会话中才真正相关的值,所以在$_SESSION中传递它是有意义的。因为我们喜欢给所有值赋予相关的标题,所以将其存储在$_SESSION['error'];中是传递错误消息的一种完全合法的方式。