防止在 PHP 中访问某个目录外的文件 [英] Prevent access to files outside a certain directory in PHP

查看:76
本文介绍了防止在 PHP 中访问某个目录外的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现通过传递一个查询字符串参数来访问网站目录外的文件,然后入侵网站,我的网站可能会被黑客入侵.

I've found out the hard way that my website can be hacked by passing a query string parameter that has many ../s to access files outside of the website directory, and then hack the website.

有没有办法,也许是通过 php.ini,不允许文件包含在某个根目录之外?

Is there a way, perhaps through the php.ini, to not allow file includes outside of a certain root directory?

更糟糕的是,服务器上运行的大部分内容都不是我的代码.该网站在 CMS Joomla 上运行!并且该漏洞是通过购买的插件完成的.

To make things worse, most of what is running on the server is not my code. The website runs on the CMS Joomla! and the exploit was done through a purchased plugin.

我无法更改脚本,如果必须更改,我将卸载受影响的插件.

I cannot change the scripts, if it has to come to that, I'll just uninstall the affected plugins.

推荐答案

是的,PHP 有一个名为 open_basedir 的配置参数正是为此目的.
(不要忘记至少添加 session_save_path 目录)

Yes, PHP has a configuration parameter called open_basedir exactly for that purpose.
(don't forget to add to it at least session_save_path directory)

但是!无论如何你必须检查每个传递的参数!

But! You have to check every passed parameter anyway!

如果它应该只是一个文件名,请使用 basename() 函数截断它.如果它应该是一个目录,你可以用这样的代码检查它

if it's supposed to be just a filename, truncate it using basename() function. if it's supposed to be a directory, you can check it with such a code

$basedir = "/your/app/path/";
$realdir = realpath($basedir.$filename); //$filename is the parameter we checking

if (substr($realdir,0,strlen($basedir)) !== $basedir) {
  header ("HTTP/1.0 403 Forbidden"); 
  exit; 
}

这篇关于防止在 PHP 中访问某个目录外的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆