如何防止通过URL直接访问php页面

时间:2013-09-26 12:43:23

标签: php include

我有index.php,其中包含

等页面
<?php

define('MyConst', TRUE);

include_once('template/header.php');

if (!empty($_GET['action'])) {  
    $action = $_GET['action'];   
    $action = basename($action);   
    include("template/$action.php");   
} else { 
    include("template/main.php"); 
} 

include_once('template/footer.php'); 

?>

在模板目录中,我有main.php,它有链接到其他页面,如page1.php,page2.php。

<a href="?action=page1">Goto page 1</a>
<a href="?action=page2">Goto page 2</a>

如何阻止用户直接在网址上输入“http://mydomain.com/?action=page1”来访问网页?如果他们已经完成了,那么将它们重定向到main.php?

5 个答案:

答案 0 :(得分:1)

你做不到。你想要的是根本不可能的。

对于服务器端,无法知道是否键入或单击了URL。

答案 1 :(得分:1)

如果我理解正确,您想要的是阻止用户访问http://example.org/?action=page1,除非他们来自http://example.org/?action=main。为此,您必须能够检测它们是否来自http://example.org/?action=main。最安全的方法是生成一些随机值,这些值在用户访问http://example.org/?action=main时与用户关联,并检查用户何时访问http://example.org/?action=page1时是否存在正确的值。如果没有,他们会尝试直接访问该页面。

答案 2 :(得分:0)

检查HTTP_REFERER,如果它没有指向正确的值(如你的页面),那么重定向用户。

答案 3 :(得分:0)

也许你可以试试这个,在你的index.php上:

session_start();
if(! isset($_GET['action']))
{
   $_SESSION['pageAccess'] = true; # Set the key whatever you want
}

然后在该脚本下(我们需要使用两次session_start()):

if(isset($_GET['action']))
{
  if(! isset($_SESSION['pageAccess']) || ! $_SESSION['pageAccess'])
     exit('There is no direct access allowed.');
}

希望得到这个帮助,祝你有个美好的一天。

答案 4 :(得分:0)

根据你的问题:

您可以遵循两种方法:

  1. 如果用户来自您想要的页面,请使用HTTP_REFFRER并检查所需的页面。如果他正在访问直接URL,则显示错误页面。
  2. 使用$_SESSION但这种方法可能有害,因为SESSION将一直存在,直到浏览器/实例关闭。
  3. 第一种方法更好。 而且根据Pehaa,您无法检查id URL是否已键入

相关问题