【问题标题】:Displaying a Username or Password Feedback Message using PHP使用 PHP 显示用户名或密码反馈消息
【发布时间】:2021-02-08 23:50:10
【问题描述】:

我需要在输入无效的用户名或密码时显示消息。

我进行了设置,以便在发生某些事情时将页面重定向回index.php 页面,但添加了?message=Bad_Username?message=Bad_Password

我还设置了一个 if 语句,以便在满足某些条件时,我可以在用户名或密码字段下方打印消息。

我只是不确定 If 语句需要什么条件才能工作。

这是代码。

if (($_GET['username'])){
    echo "<p class='help is-danger'>This username is invalid</p>";
    if(header("location: index.php?message=Bad_Username")){
        echo "<p class='help is-danger'>This username is invalid</p>";
    }
}

【问题讨论】:

  • $_GET 只是一个数组。知道了这一点,您可以检查键和特定值的存在。 if (isset($_GET['message']) &amp;&amp; $_GET['message'] === 'Bad_Username')) { ...
  • if(header... 完全没有意义。根据php.net/manual/en/function.header.phpheader() 不返回值,因此对if 进行评估没有任何用处。即使确实如此,也不清楚您要通过这样的声明来实现什么。设置重定向标头告诉浏览器忽略当前响应并转到另一个页面。因此,在当前响应中回显某些内容是没有意义的,因为您刚刚告诉浏览器忽略它。

标签: php if-statement message feedback


【解决方案1】:

如果你在get中收到东西,说明用户名不正确。如果您没有收到任何内容,则表示该用户尚未尝试连接。

只需在您的登录页面(您有表单的地方)执行此操作:

if ($_GET['message']==Bad_UserName) {
        echo "<p class='help is-danger'>This username is invalid</p>";
    }

如果你想对用户名和密码都这样做,你可以这样做:

if ($_GET['message']==Both_Bad) {
    echo "<p class='help is-danger'>This username and password 
          are invalid</p>";
}
if ($_GET['message']==Bad_Username) {
    echo "<p class='help is-danger'>This username is invalid</p>";
}
if ($_GET['message']==Bad_Password) {
    echo "<p class='help is-danger'>This password is invalid</p>";
}

这是您的登录处理示例:

$user="user1"; //user example
$pass="1234"; //pass example

//method post or get (depends on your form method)
$inputUser = filter_var($_POST['user'], FILTER_SANITIZE_STRING);
$inputPass = filter_var($_POST['pass'], FILTER_SANITIZE_STRING);

if($inputUser!=$user && $inputPass!=$pass){
    header("location: index.php?message=Both_Bad");
}elseif ($inputUser!=$user) {
    header("location: index.php?message=Bad_Username");
}elseif ($inputPass!=$pass) {
    header("location: index.php?message=Bad_Password");
}else{
    $_SESSION['user'] = $inputUser //can be the login, id of the user or something else
    header("location: MyNextPage.php");
}

登录页面和登录处理分为两个文件

【讨论】:

    猜你喜欢
    • 2022-01-15
    • 1970-01-01
    • 2018-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多