防止任何人可以直接在他的浏览器中打开包含文件

Prevent that anybody can open include file directly in his browser

我有一个名为 startpage.inc.php 的文件,我想包含它但要防止任何人都可以在他的浏览器中打开它。可能吗?

可能:

<?php
include 'inc/startpage.inc.php';
?>

防止:

www.example.org/inc/startpage.inc.php

您有多种选择。

  • 检查您的文件中是否定义了常量。如果没有,exit;。在包含您的 startpage.inc.php 的文件中定义一个常量。这就是许多免费脚本防止不需要的包含的方式。

  • 公开文件夹中没有脚本。将其移到文档根目录下,这样就永远无法直接访问它,只有通过 includerequire.

  • 包含时才能访问

有很多方法可以做到这一点,包括 .htaccessphp,即:

使用PHP:

if(count(get_included_files()) ==1) exit("Direct access denied.");

使用.htaccess 文件

<FilesMatch "\.inc\.php$">
    Order deny,allow
    Deny from all
</FilesMatch>

花点时间阅读: best-5-ways-to-prevent-direct-access-to-a-php-file