如何防止直接访问 PHP 页面

How to prevent a PHP page from being accessed directly?

本文关键字:PHP 页面 访问 何防止      更新时间:2023-09-26

下面是一个JavaScript片段,我将其用作AJAX脚本的一部分。 如何防止直接访问user_back_end_friends.php? 我不希望人们能够去 domain.com/user_back_end_friends.php 看到朋友名单。

Javascript 代码:

<script type="text/javascript">
    $(document).ready(function() {
        $("#user_friends").tokenInput("/user_back_end_friends.php", {
            theme: "sometheme", userid: "<?php echo $id; ?>"
        });
    });
</script>

这是我发现的,但不确定如何使用上面的 javascript 代码实现它:

我在需要调用它的页面中使用它:

$included=1;include("user_back_end_friends.php");

当我必须阻止直接访问时,我使用:

if(!$included){ die("Error"); }

但是如何在我的 JavaScript 代码中添加这个$included脚本的一部分呢?

保护javascript代码没有意义,你只需要保护服务器端代码。

无论如何,我认为你的方法不正确;如果你已经有一个登录的用户/用户ID,我只会使用会话中的用户ID,而不是javascript提供的用户ID。这样就没有人可以篡改它。

因此,您可以通过以下方式开始您的页面:

session_start();
if (isset($_SESSION['user_id'))
{
  // do stuff with the user ID
}
else
{
  // display error message?
}

由于 Web 的本质,您无法完全阻止对此脚本的访问。

您可以检查引荐来源网址信息、输入验证,您可以在父页面上创建一个在子页面上检查的会话变量。

我已经做了以下工作。请注意,这不是最安全的,正如其他答案所提到的,您无法完全阻止对此脚本的访问(提供了指向简单绕过的链接),但出于我的简单目的,这运行良好 -

define('_REFERURL',              'http://www.example.com');            // This is the full URL of your domain that will be calling your PHP script(s)

然后创建一个函数来检查引用 URL(应该来自您的域)

function allow_user()
{
        if ($_SERVER['HTTP_REFERER'] == _REFERURL)
        {
                return true;
        }
        else
        {
                return false;
        }
}

用:

if (allow_user())
{
     // Do things
}
else
{
     // Alert, direct access attempted
}

轻松通过:http://www.datatrendsoftware.com/spoof.html