重定向&请求登录以保护直接写入的URL

时间:2016-06-29 15:52:49

标签: php redirect

目前我一直在尝试创建一个非常简单的登录页面。但是我想稍微远一点。

我在当地工作。 假设我们有一个index.php和login.php页面。 当我在url栏上写localhost:8080 / index.php时,我能够查看此页面。但我希望它需要登录才能重定向到index.php页面。

这是login.php代码,我不知道如何在输入网址时重定向它,

<html>
<head></head>
<body>
<form method="post" name="login" action="">
<table align=center>
    <tr>
        <td><input type="text" name="username" placeholder="Username"></td>
    </tr>
    <tr>
        <td><input type="text" name="password" placeholder="Password"></td>
    </tr>
    <tr>
        <td><input type="submit" name="submit" value="Login"></td>
    </tr>
</table>
</form>

<?php



    if (isset($_POST['submit']))
    {
        $username="admin";
        $password="admin";
        $uUsername=$_POST['username'];  // the username which User will enter
        $uPassword = $_POST['password'];// the password which User will enter

        if  ( $username != $uUsername || $password != $uPassword )
        {
            echo 'Incorrect username or password.Please try again';
        }

        else
        {
            header("refresh:0; url=deneme.php");
        }
    }
?>

1 个答案:

答案 0 :(得分:0)

首先,在向浏览器输出任何内容之前,您需要检查用户是否经过身份验证,因为在任何输出之前必须调用header()。我会使用会话。

在每个需要经过身份验证的用户的文件的顶部(登录页面除外),我会添加:

<?php
session_start();
if (!isset($_SESSION['authenticated'])) {
    // The user isn't authenticated, let's redirect the user to the login page
    header('location: login.php'); // Change 'login.php' to the correct page/url to the login page.
    exit; // Important to stop the script-execution after a header location.
}

如果未设置会话(用户未经过身份验证),则会将用户重定向到登录页面。

在登录页面上,我会将身份验证脚本移到文件顶部(<html>之前),并将其更改为:

<?php
$errorMessage = null;

if (isset($_POST['submit'])) {
    $username  = "admin";
    $password  = "admin";
    $uUsername = $_POST['username'];
    $uPassword = $_POST['password'];

    if  ( $username != $uUsername || $password != $uPassword ) {
        $errorMessage = 'Incorrect username or password. Please try again';
    } else {
        // Start the session and set authenticated as true.
        session_start();
        $_SESSION['authenticated'] = true;
        header('location: index.php'); // Again, change 'index.php' to the correct file/url
        exit;
    }
}
?>
<html>
....// the rest of the login form

在表单的下方,您可以检查$errorMessage是否null并显示错误消息。

应将身份验证检查的代码移动到一个单独的文件中,该文件包含在每个文件中,而不是每个文件中的硬编码。