0

我试图在 stackoverflow 和网络上的其他地方搜索这个。

似乎无法牢牢锁定表明这是最安全方式的答案。

我知道最安全的方法是在可能的情况下不在根目录中包含任何可以提供帮助的 php 文件。

所以,我想知道的是,如果我想包含一个存储在根目录之外的 php 文件,比如说,在另一个目录中,那么对我来说最安全的方法是什么?

4

2 回答 2

1

这不会直接回答您的问题,但也许它会让您以不同的方式看待您的应用程序结构。我认为包含来自 webroot 外部的文件是不安全的,这是一种误解。

相反,许多人的结构中,如果不是全部的话,他们的应用程序逻辑大部分都在该public_html目录或类似目录之外。特别是对于包罗万象的路由器类型系统。

你可以有这样的结构:

var
    www
        public
            something.js
            happy.jpg
            index.php
        application
            bootstrap.php
            AwesomeClass.php
            Router.php

现在有了您index.php,您就可以找出应用程序的真正根源。

就像是:

define('WEB_ROOT', __DIR__);
define('APP_ROOT', dirname(__DIR__));
define('PHP_ROOT', APP_ROOT . DIRECTORY_SEPARATOR . 'application');

You now have constants that point to the real filesystem path of your public html directory and where your php files are, and can now safely include files like:

include(PHP_ROOT . DIRECTORY_SEPARATOR . 'bootstrap.php');

This is perfectly safe, and many people have apps structured like this. It also prevents people being able to browse to any php files you have laying around, in the event that you don't have any .htaccess or similar voodoo in place.

于 2012-07-07T11:15:20.230 回答
0

根据您的问题,我相信您想防止目录遍历(人们试图让您的脚本包含 /etc/passwd 等)。

在请求的路径上使用realpath 。这应该扩展所有../..

完成此操作后,您可以根据realpath()白名单检查返回的结果或将其限制在您自己的目录中并检查file_exist():是否file_exist('myfolder' . DIRECTORY_SEPERATOR . $resultFromRealPath())

于 2012-07-07T10:56:59.673 回答