PHP - 错误的用户名/密码 - 如何正确回应它

时间:2015-03-13 03:22:58

标签: php mysql username

我正在尝试用PHP编写登录表单。登录/注销工作正常,但我对回应的正确方法有点好奇#34;错误的用户名/密码"对于我的特定代码。

这是我的代码(来自login.php,它包含在侧边栏的index.php中):

<form method="post" action="security.php">
<input name="username" type="text" placeholder="Username" id="username"><br />
<input name="password" type="password" placeholder="Password" id="password"><br />
<input name="login" type="submit" value="Log in" class="login">
<small><input type="checkbox"> Keep me logged in</small>
</form>
<?php
if ($failed == 1) {
echo "Wrong Username / Password";
}
?>

这是我的security.php代码:

<?php
require 'connect.php';

// username and password sent from form 
$tbl_name = 'users';
$username=$_POST['username']; 
$password=$_POST['password'];

// To protect MySQL injection
$username = stripslashes($username);
$password = stripslashes($password);
$username = mysqli_real_escape_string($conn, $_POST['username']);
$password = mysqli_real_escape_string($conn, $_POST['password']);
$sql="SELECT * FROM $tbl_name WHERE username='$username' and password='$password'";
$result = mysqli_query($conn, $sql);

// Mysql_num_row is counting table row
$count = mysqli_num_rows($result);

// If result matched $username and $password, table row must be 1 row
if($count == 1)
{
// Register $username, $password and redirect to file "login_success.php"
session_start();
$_SESSION["username"] = $username;
header("location:home.php");
}
else {
$failed = 1;
header("location:index.php");
}
?>

正如您可能看到或未看到的那样,我尝试在security.php中使用名为$ failed的变量集,该变量在security.php中设置并在login.php中的if中用于回显失败消息。我知道这甚至不接近工作,但这是我能看到告诉你我想做什么的唯一方法。有什么帮助吗?

3 个答案:

答案 0 :(得分:1)

试试 security.php

if($count == 1)
{
// Register $username, $password and redirect to file "login_success.php"
session_start();
$_SESSION["username"] = $username;
header("location:home.php");
}
else {
header("location:index.php?msg=failed");
}

这是 index.php:

if (isset($_GET["msg"]) && $_GET["msg"] == 'failed') {
echo "Wrong Username / Password";
}

答案 1 :(得分:0)

您应该在您的SQL查询中添加LIMIT 1。

否则请执行header("location:index.php?success=false");

然后你可以检查它:

if( !empty( $_GET[ 'success' ] ) && ( $_GET[ 'success' ] == FALSE ) )
{
echo 'failed login';
}

答案 2 :(得分:0)

在您的安全代码中,您可以在登录失败部分更改:

$failed = 1;
header("location:index.php");

为:

$failed = 1;
include "./login.php";

这样,当身份验证失败时,用户将返回到登录屏幕,而不会在其间进行301重定向。如果所有php文件都在同一个文件夹中,这将很有效。