php 限制直接页面访问
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6867013/
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
Restrict direct page access
提问by George
In attempt of securing an administrator area of a site I'm working on I made an index.php which contains
为了保护我正在处理的站点的管理员区域,我创建了一个 index.php,其中包含
if (isset($_POST['password']) && isset($_POST['userName'])) {
if($_POST['password']==$pass && $_POST['userName']==$username)
{
header( 'Location: admin.php' ) ;
}
This redirects to a file in the same folder called admin.php. The problem is that I can access this file if I write localhost/folder/admin.php
. Please tell me how to restrict the direct access to this page. The only way accesing it should be from index.php after username and password.
这将重定向到名为 admin.php 的同一文件夹中的文件。问题是我可以访问这个文件,如果我写localhost/folder/admin.php
. 请告诉我如何限制对该页面的直接访问。访问它的唯一方法应该是在用户名和密码之后从 index.php。
回答by genesis
set a session variable and check it everytimes somebody access admin.php
设置会话变量并在每次有人访问 admin.php 时检查它
<?php
if (isset($_POST['password']) && isset($_POST['userName'])) {
if ($_POST['password'] == $pass && $_POST['userName'] == $username) {
if (!session_id())
session_start();
$_SESSION['logon'] = true;
header('Location: admin.php');
die();
}
?>
and
和
//admin.php
if (!session_id()) session_start();
if (!$_SESSION['logon']){
header("Location:index.php");
die();
}
回答by Brad Morris
You should look into PHP sessions. You can set a session variable "isLogged" in that redirection file, and then check in admin.php if that session variable is registered, if not redirect to the login page!
您应该查看 PHP 会话。您可以在该重定向文件中设置一个会话变量“isLogged”,然后在 admin.php 中检查该会话变量是否已注册,如果没有则重定向到登录页面!
session_start();
if (isset($_POST['password']) && isset($_POST['userName'])) {
if($_POST['password']==$pass && $_POST['userName']==$username)
{
header( 'Location: admin.php' ) ;
$_SESSION['isLogged'] = true;
}
admin.php
管理文件
session_start();
if(!$_SESSION['isLogged']) {
header("location:login.php");
die();
}
Note: session_start(); must be called before the $_SESSION global can be utilised.
注意:session_start(); 必须在使用 $_SESSION 全局之前调用。
回答by deceze
Set a session value that signifies that a user has successfully logged in, check for it on every page you want secured, redirect to login if that value isn't set.
设置一个会话值,表示用户已成功登录,在您想要保护的每个页面上检查它,如果未设置该值,则重定向到登录。