[英]How to prevent direct access to files in folder?
有一个网页,其中的“ subdir”具有以下结构:
index.php在/ system中调用file1.php。 然后/ system中的其他文件被“提交”调用。 我无法编写正确的.htaccess来防止直接通过其URL调用这些/ system / 。
我用谷歌搜索并尝试了各种.htaccess内容。 但是大多数情况下, “ subdir”根本无法访问(甚至不能从index.php ),或者“ webpage”访问返回“ 404” 。
通常,用户应打开index.php并决定要执行的操作。 依赖于此,他被重定向到相应的/ system / .php。 任何其他尝试/例如添加https:// mywebpage / subdir / system / anyfile 。 应将他重定向回index.php或任何其他“错误页面”。
典型的方法是在入口点(如index.php)中定义一个先于其他文件运行的全局常量,然后检查每个文件是否定义了该常量
define('SOME_CONST', true);
然后在每个文件的顶部
if(!defined('SOME_CONST')) die ("No direct access");
因此在不首先加载定义常量的文件的情况下访问文件将导致PHP终止。
这个“常量”可以是任何东西,通常我使用相对于index.php文件等的基本路径。
define('MY_BASE_PATH', __DIR__.'/');
等等...
注意事项
我应该提到您不应该在文件中定义它并将其包含在其他文件中,否则它将无法正常工作。
//DO NOT DO THIS as IT wont WORK!!!!! - technically it never fails
//--- in the file somefile.php ---
//required file defines SOME_CONST
require 'index.php';
//define('SOME_CONST', true); -- defined in index.php, think of it like copy and pasting that files code at this spot.
//will never fail, because it's defined by the file included/required above
if(!defined('SOME_CONST')) die ("No direct access");
这就像将其放入您的代码中并期望它会失败(显然,这里永远不会失败):
//dont do this either
define('SOME_CONST', true);
if(!defined('SOME_CONST')) die ("No direct access");
而是这样做:
因此,您必须包括该入口点的文件,并使用路由器等...基本的MVC。 改为这样做(大大简化了)
// --- in index.php ---
define('SOME_CONST', true);
require 'somepage.php';
//if(!defined('SOME_CONST')) die ("No direct access"); included in the above require
接着
//--- in somefile.php ---
if(!defined('SOME_CONST')) die ("No direct access"); //will fail if index.php is not loaded.
因此,如果有人只访问somefile.php
该常量未定义。 因为没有在该文件“之前”执行index.php
。...如果您在检查之前包括index.php
(在somefile.php
),则不喜欢。 您显然不能在检查后包括它( index.php
)。 因此它必须在somefile.php
之前运行,而不是仅在加载somefile.php
时运行。 这就是为什么您不能在somefile.php
包含index.php
,而必须在index.php
包含somefile.php
的原因。
同样显然,您将需要多于一页的somefile.php
。 因此,在索引中,您将需要一种将请求定向到正确页面的方法。 这称为路由。 这是另一个主题...
我试图使它尽可能基本。 这真的很简单。
请享用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.