如何限制PHP中的文件系统访问?

编程入门 行业动态 更新时间:2024-10-24 08:19:15
本文介绍了如何限制PHP中的文件系统访问?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

有人知道使PHP脚本自动限制对文件系统(fopen,file_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 或 runkit_function_rename ,然后使用您自己的逻辑包装重命名的版本.

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中的文件系统访问?

本文发布于:2023-10-31 18:43:36,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1546949.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:文件系统   PHP

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!