【发布时间】:2011-08-03 17:34:35
【问题描述】:
这是我的文件结构示例。
/index.php
/inc
/inc/file1.php
/inc/file2.php
/inc/file3.php
/search.php
index.php 包括() file1.php、file2.php 和 file3.php。 我希望它们只能由 index.php 访问。
最优雅的解决方案是什么?
谢谢
【问题讨论】:
这是我的文件结构示例。
/index.php
/inc
/inc/file1.php
/inc/file2.php
/inc/file3.php
/search.php
index.php 包括() file1.php、file2.php 和 file3.php。 我希望它们只能由 index.php 访问。
最优雅的解决方案是什么?
谢谢
【问题讨论】:
将它们放在文档根目录之外:
/documentroot/index.php
/inc/file1.php
/inc/file2.php
/inc/file3.php
因此,无论如何都无法直接访问它们。
【讨论】:
.htaccess 是允许的,则在 /inc 中放入一个 .htaccess 文件,其中包含以下行:Order allow,deny & Deny from all。
在 index.php 中你可以像这样定义一个常量:
define('RESTRICTED',1);
然后在你的其他页面中,你把它放在<?php之后
if(!defined('RESTRICTED'))exit('No direct script access allowed!');
当直接访问其他页面时,上面的代码看到 RESTRICTED 尚未设置,因此它将退出。
【讨论】:
制作一个 .htaccess 文件并将其放入 inc 文件夹中
<Files .htaccess>
order allow,deny
deny from all
</Files>
<Files *.php>
order allow,deny
deny from all
</Files>
或者把它放在你想拒绝的文件的顶部
if(strrchr($_SERVER['PHP_SELF'],'/')=='/file_name.php'){die;} // not good for ajax include
【讨论】: