如何使用文件系统访问限制PHP脚本?

时间:2010-01-06 14:36:45

标签: php

我有一个PHP脚本,可以尝试访问具有敏感数据的目录中的文件。我想限制这种操作。

我想允许此脚本仅在我指定的目录中访问文件/目录。有可能吗?感谢。

4 个答案:

答案 0 :(得分:2)

是的,只需编写脚本,以便它只访问安全目录中的文件。不要(永远)从用户输入中未经检查的路径访问文件。根据可接受路径和/或文件名列表检查路径,或在代码中包含将访问文件的路径,以便只将文件名传递给访问代码。

这些功能有助于: pathinfo()dirname()basename()

答案 1 :(得分:2)

免责声明:如果您不控制在服务器上设置PHP的方式,那么这个答案就没用了。

我们确实需要有关PHP设置的更多信息,例如它使用的Web服务器以及SAPI模式。您可以通过运行echo php_sapi_name()

找出正在使用的SAPI模块

但是,如果我假设它是带有mod_php的Apache 2.2:

PHP的Apache模块版本作为Web服务器的用户和组运行。还有第二个名为suPHP的Apache模块,它包装了PHP CGI版本,使其作为脚本的所有者和组运行(并且避免了为PHP手动设置Apache的suEXEC)。

除此之外,更改文件系统的权限,以便用户对敏感目录及其文件没有读取权限应该足够好。

答案 2 :(得分:1)

这样的事情应该有效:

function isBelowAllowedPath($file, $allowedPath)
{
    return ( strpos( realpath($file), $allowedPath) === 0 );
}

isBelowAllowedPath('/etc/passwd', '/var/www/pub/'); // false
isBelowAllowedPath('/var/www/pub/index.htm', '/var/www/pub/'); // true

或者如果你想确保$ file也存在

function isBelowAllowedPath($file, $allowedPath)
{
    return file_exists( $allowedPath . basename(realpath($file)) );
}

isBelowAllowedPath('/../../../../etc/passwd', '/var/www/pub/'); // false
isBelowAllowedPath('index.htm', '/var/www/pub/'); // true

或者如果您希望$ file位于$ allowedPaths的特定列表中(不在路径下方)

function isInAllowedPath($file, array $allowedPath)
{
    $fileDir = realpath(dirname($file));
    return (in_array($fileDir, $allowedPath));
}

$allowed = array('/var/www/pub/', 'somewhere/else');
isInAllowedPath('/var/www/pub/foo/index.htm', $allowed); // false
isInAllowedPath('/var/www/pub/index.htm', $allowed); // true

答案 3 :(得分:0)

您必须配置目录的权限,以便用户PHP无法访问它们。

要在Linux / Unix系统上执行此操作,您需要有权更改目录的所有者(chown)并更改其权限(chmod)以及可能的命令行访问权限。这实际上取决于服务器的配置方式,拥有文件的人员以及PHP运行的对象。

要在Linux系统上查找PHP用户的用户ID,请使用posix_getuid()

除了通过disable_functions删除对某些功能的访问权限之外,我无法想到保护文件免受PHP端访问的其他方法。但是,这可能(也可能会)打破许多合法行为。