如何使用 PHP 将登录表单错误返回到同一页面?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9485059/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 06:55:36  来源:igfitidea点击:

How do you return login form errors to the same page using PHP?

phphtmlformslogin

提问by Callum O' Riordan

I'm relatively new to PHP and have exhausted the internet trying to find an answer to this problem. I've looked at countless examples but people seem to very different login systems to mine and I have trouble deciphering it.

我对 PHP 比较陌生,并且已经用尽互联网试图找到这个问题的答案。我看过无数的例子,但人们似乎对我的登录系统有很大的不同,我很难破译它。

Here is my code so far:

到目前为止,这是我的代码:

index.html

索引.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Video for Education Log In</title>
<link rel="stylesheet" type="text/css" href="style.css" />
</head>



<body>
<div id="wrapper">
<div id="header">
    <div id="logo">
        videoedu.edu    </div>
    <div id="menu">
        <ul>
            <li><a href="account.html" class="menua">Create Account</a></li>
            <li><a href="about.html" class="menua">About Us</a></li>
        </ul>
    </div>
</div>
<br><br><br><br>
<div id="page">

<div id="content">
    <h2>Video for Education helps you connect and share with the videos in your life.</h2>
    <h3>Upload Share Create Using video for your education purposes. Lecturers Welcome
    Upload Share Create Using video for your education purposes. Lecturers Welcome
    Upload Share Create Using video for your education purposes. Lecturers Welcome</h3>
    <div class= "form">
    <form name="login" method="post" action="checklogin.php">
        Username: <input type="text" name="myusername" id="myusername" class="textb"/><br />
        Password  :  <input type="password" name="mypassword" id="mypassword" class="textb"/><br />
        <br>
        <input type="submit" name="login" value="Login" id="login" class="texta" />
    </form>
    </div>
</div>
</div>
</div>
</body>
</html>

checklogin.php

检查登录.php

<?php

$host = "localhost";
$username = "root";
$password = "";
$db_name = "test";
$tbl_name = "members";

mysql_connect("$host", "$username", "$password")or die("Cannot connect.");
mysql_select_db("$db_name")or die("Cannot select DB.");

$myusername=$_POST["myusername"];
$mypassword=$_POST["mypassword"];


    if ($myusername&&$mypassword)
    {

    $myusername = stripslashes($myusername);
    $mypassword = stripslashes($mypassword);
    $myusername = mysql_real_escape_string($myusername);
    $mypassword = mysql_real_escape_string($mypassword);

    $sql = "SELECT * FROM $tbl_name WHERE username='$myusername' and password='$mypassword'";
    $result = mysql_query($sql);

    $count = mysql_num_rows($result);

    if($count == 1){
    session_register("myusername");
    session_register("mypassword"); 
    header("location:login_success.php");
        }
    else 
        {
    echo "Wrong Username or Password";
        }
    }

    else

    echo "You have left one or more fields blank.";

?>

login_success.php

login_success.php

<? 
session_start();
if( !isset( $_SESSION['myusername'] ) ){
header("location:account.html");
}

echo "Welcome, ".$_SESSION['myusername']." - You are now logged in.<br>";

echo "<a href=logout.php>Logout</a>"
?>

<html>
<body>

</body>
</html>

logout.php

登出.php

<?php

session_start();

session_destroy();

echo "You have been logged out, <a href='index.php'>click here</a> to return."

?>

I have tried inserting this into index.html and changing the file name to index.php.

我尝试将其插入 index.html 并将文件名更改为 index.php。

$submit = $_POST["login"];

if($submit)
{

}

...but it just constantly displays one of the errors ('Wrong username or password') down the bottom of the page at all times.

...但它只是不断地在页面底部始终显示一个错误(“错误的用户名或密码”)。

I want it so that if the user enters a wrong username or password, or leaves a required field blank, the error will pop up on the same page, instead of going to a new ugly, blank PHP page with the error message in the top left-hand corner.

我想要这样,如果用户输入错误的用户名或密码,或者将必填字段留空,错误将在同一页面上弹出,而不是转到一个新的丑陋的空白 PHP 页面,并在顶部显示错误消息左角。

采纳答案by Travesty3

In checklogin.php, instead of echoing an error, use this:

在 checklogin.php 中,不要回显错误,而是使用以下命令:

die(header("location:index.html?loginFailed=true&reason=password"));

or something similar, and in your index.html page, just have PHP generate the HTML message, something like this:

或类似的东西,在您的 index.html 页面中,只需让 PHP 生成 HTML 消息,如下所示:

    <input type="submit" name="login" value="Login" id="login" class="texta" /><br /><br />
    <?php $reasons = array("password" => "Wrong Username or Password", "blank" => "You have left one or more fields blank."); if ($_GET["loginFailed"]) echo $reasons[$_GET["reason"]]; ?>
</form>

Also, make sure to die()or exit()when you use headerto redirect the page, otherwise the rest of your script continues to run.

此外,请确保die()exit()当您使用header重定向页面时,否则脚本的其余部分将继续运行。

回答by Senad Me?kin

What you can do is, redirect back to your page if data is invalid. Put errors into session and display them on page:

您可以做的是,如果数据无效,则重定向回您的页面。将错误放入会话并显示在页面上:

e.g.:

例如:

<?php if(isset($_SESSION['Login.Error'])  { echo $_SESSION['Login.Error'];
 unset($_SESSION['Login.Error']); } ?>
<form ....

and your error will be visible on page.

并且您的错误将在页面上可见。

In your PHP

在你的 PHP

 $_SESSION["Login.Error"] = 'Invalid credentials';//redirect back to your login page

回答by Ian

In checklogin.php, if the user enters a wrong username or password, use the code like this:

在 checklogin.php 中,如果用户输入了错误的用户名或密码,使用如下代码:

echo "<script language=\"JavaScript\">\n";
echo "alert('Username or Password was incorrect!');\n";
echo "window.location='login.php'";
echo "</script>";

It will pop up the error message at the same page (login page), instead of going to a blank PHP page.

它会在同一页面(登录页面)弹出错误信息,而不是跳转到空白的 PHP 页面。

回答by msmafra

It looks like you want/need to integrate it with jQuery or some other Javascript/AJAX library to make things more presentable. jQuery has an plugin for form validation that's is very easy to integrate to your project (obviously jQuery library is minimum requirement). jQuery siteand jQuery validation plugin. You may also consider using a PHP Framework like CodeIgniterwhich is also has a very helpful form validation library. CodeIgniter is scary at the beginning (like all MVC based programming library/framework) but it's worth it. you can watch some tutorials on netTuts+ they've created a series of tutorials called CodeIgniter From Scratch, is not from the latest version but is easy to adapt.

看起来您想要/需要将它与 jQuery 或其他一些 Javascript/AJAX 库集成,以使事情更易于展示。jQuery 有一个表单验证插件,它很容易集成到您的项目中(显然 jQuery 库是最低要求)。 jQuery 站点jQuery 验证插件。您也可以考虑使用像CodeIgniter这样的 PHP 框架,它也有一个非常有用的表单验证库。CodeIgniter 一开始很可怕(就像所有基于 MVC 的编程库/框架一样),但它是值得的。你可以在 netTuts+ 上观看一些教程,他们创建了一系列名为CodeIgniter From Scratch的教程,不是最新版本,但很容易适应。

回答by thescientist

You would want to make your index.html page a PHP page, and have the form submit to itself, i.e. to index.php. In this way, you your index page can do the login check for the form values and display the output of the page appropriately, or use headers to redirect if everything validates.

您可能想让 index.html 页面成为 PHP 页面,并将表单提交给自身,即 index.php。通过这种方式,您的索引页面可以对表单值进行登录检查并适当地显示页面的输出,或者如果一切都通过验证,则使用标题进行重定向。

It's hard to tell the effect that your attempt may have had without seeing it in the full context, but the gist of the situation is you need the form to submit to itself and handle it's login processing.

如果没有在完整的上下文中看到它,很难说出您的尝试可能产生的效果,但情况的要点是您需要表单提交给自身并处理它的登录处理。