如何允许 PHP 写入文件而不影响服务器安全
每当我想让 PHP 脚本将输出写入服务器上的文件时,我经常会遇到负面评论。
我使用 fopen()
、fwrite()
和 fclose()
函数。
我知道如何实现这一点的唯一方法是将输出文件的权限设置为 0666 或将其归“nobody”所有(这是 PHP 在我们的 Apache Web 服务器上运行的用户)。
那么,如果“0666”或“无人拥有”存在安全风险,那么如何成功且安全地允许 PHP 脚本写入文件?
感谢您分享有关此主题的指导。
I am often confronted with negative comments whenever I want to have a PHP script write output to a file on the server.
I use the fopen()
, fwrite()
and fclose()
functions.
The only way I know how to make this happen is to either set the permissions for the output file to 0666 or have it owned by "nobody" (which is the user that PHP runs under on our Apache web server).
So, if "0666" or "owned by nobody" are security risks, how do you successfully and securely allow a PHP script to write to a file?
Thanks for sharing guidance on this topic.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您需要在上传后从 PHP 访问文件,那么需要使用允许 Web 服务器(在本例中为 apache)访问它们的权限来存储它们。人们所说的风险是您网站上的某些脚本可能会被欺骗而提供该文件。这是一种假设的风险,但许多内容管理系统都发生过这种风险。为了减轻这种风险:
getfile.php?file=1.txt
的路径,他们可以轻松推断也有2.txt
。隐藏名称或使其不排序。/etc/passwd
等的恶意引用。如果您只需要删除文件并且不再提供它或再次通过 PHP 访问它,您还有更多选择。使用 chmod 或 chown 命令使其对 apache 用户来说不可读。如果您想更加偏执,可以使用 cron 脚本将文件(并重命名)移动到 PHP 源代码中未知的位置。至少,如果您的服务器被黑客攻击,入侵者无法直接进入该目录,但我们正在接近讨论转向操作系统安全的地步。
If you need to access the files from PHP after they are uploaded then they need to be stored with permissions that let the web server (apache in this case) access them. The risk that people speak of is that some script on your site could be fooled into serving up the file. It is a hypothetical risk, but one that has occurred with many Content Management Systems. To mitigate this risk:
getfile.php?file=1.txt
they can readily infer that there is a2.txt
as well. Crypt the name or make it unsequenced./etc/passwd
and the like.If you just need to drop the file off and never serve it or access it via PHP again, you have some more options. Either use the
chmod
orchown
commands to make it unreadable to the apache user. If you want to be extra paranoid, have a cron script move the file (and rename it) to a location unknown within the PHP source. At least then if your server is hacked the intruder can't walk right into the directory, but we are getting toward the point where the discussion veers into operating system security.风险在于该可写目录是否驻留在外界可访问的区域中。然后那些拥有正确工具并且知道如何将他们想要的任何内容写入该目录...或文件的人。然后他们可以在其中放置恶意软件或在您的网站上创建网络钓鱼计划。
事实上,他们可以做各种各样的事情来损害你。我在自己的服务器上看到过这种情况,但还没有真正找到正确的解决方案。
The risk is if that writable directory resides in an area accessible to the outside world. Then those with the right tools and know how can write anything they want to that directory... or file. They can then place malware in it or create a phishing scheme on your site.
Really they can do all kinds of things to compromise you. I have seen this on my own servers and haven't really found the right solution to this.