如何限制PHP中的文件系统访问? [英] How to restrict file system access in PHP?

查看:90
本文介绍了如何限制PHP中的文件系统访问?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人知道使PHP脚本自动限制对文件系统(fopenfile_get_contents等)的访问的诀窍吗?

Someone knows a trick to have a PHP script self-restrict access to the file system (fopen, file_get_contents etc.)?

对于少数选定的文件名(日志文件,对/tmp的访问权限等),应除外阻止此类调用.

Such calls should be blocked except for a handful of selected file names (log file, access to /tmp and similar).

这不是安全问题,而是一种强制开发团队直接访问文件系统 (并检测到点在现有代码中(如果已经存在).在这种情况下,我们希望看到一个异常(被捕获并报告),因为此类文件的内容必须通过其他方式进行访问.

This is not a security thing, but rather a means of forcing the development team not to access the file system directly (and detect spots in existing code, where this is already the case). We want to see an exception in that case (which gets caught and reported), as the content of such files must be accessed by other means.

我正在考虑为file://协议实现自己的 streamWrapper ,但显然没有办法扩展内置的filewrapper类.

I was thinking about implementing my own streamWrapper for the file:// protocol, but apparently there is no way to extend the built-in filewrapper class.

推荐答案

选项1

您可以使用 open_basedir 这是一个php .ini指令以限制应用程序也可以访问的目录.这些目录可以用分号分隔,因此您可以只列出希望应用访问的目录,包括/tmp文件夹.

You can use open_basedir which is a php.ini directive to limit the directories the app has access too. The directories can be semicolon separated so you can just list the directories you want the app to access including the /tmp folder.

需要注意的是,这也会影响诸如include,require之类的事情.

The caveat is that this also affects things like include, require.

选项#2

您可以使用 rename_function

You could rename them using rename_function or runkit_function_rename and then wrap the renamed versions with your own logic.

文档引用:

在全局函数表中将orig_name重命名为new_name.有用 暂时覆盖内置函数.

Renames a orig_name to new_name in the global function table. Useful for temporarily overriding built-in functions.

示例:

rename_function('file_get_contents', 'nouse_file_get_contents');

function file_get_contents($filename, $use_include_path = false, $context, $offset = -1, $maxlen) {
    //
    // Do some validation here
    //
    return nouse_file_get_contents($filename, $use_include_path, $context, $offset, $maxlen);
}

选项3

您可以为开发人员设置一些编码标准,并编写一些单元测试,这些单元测试将在产品投入生产之前作为部署的一部分运行.不确定发布程序是什么,但是在生产之前应该捕获这些类型的东西.

You could setup some coding standards for your devs and write some unit tests that run as part of the deployment before things are pushed to production. Not sure what your release procedures are but these types of things should be caught before production.

这篇关于如何限制PHP中的文件系统访问?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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