如何允许PHP在不损害服务器安全性的情况下写入文件

如何允许PHP在不损害服务器安全性的情况下写入文件

本文介绍了如何允许PHP在不损害服务器安全性的情况下写入文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每当我想让PHP脚本将输出写入服务器上的文件时,我经常会遇到负面评论.

我使用fopen()fwrite()fclose()函数.

我知道如何做到这一点的唯一方法是将输出文件的权限设置为0666或由"nobody"(PHP在我们的Apache Web服务器上运行的用户)所有. /p>

那么,如果"0666"或没有人拥有"存在安全风险,那么如何成功,安全地允许PHP脚本写入文件?

感谢您分享有关此主题的指南.

解决方案

如果上传后需要从PHP访问文件,则需要以允许Web服务器(在这种情况下为Apache)访问的权限进行存储他们.人们谈论的风险是,您网站上的某些脚本可能会被欺骗来提供文件.这是一种假设风险,但是许多内容管理系统都已发生这种风险.为减轻这种风险:

  1. 使文件名和路径不容易猜测.如果用户有通向getfile.php?file=1.txt的路径,他们可以很容易地推断出也存在2.txt.加密名称或不加名称.
  2. 使提供文件的任何脚本确认诸如登录的用户,对资源的授权之类的内容,并从文件名中剥离任何包含路径的内容,以避免流氓引用/etc/passwd等.

如果只需要删除文件而不再提供文件或再次通过PHP进行访问,则还有更多选择.使用chmodchown命令使其对apache用户不可读.如果您想让自己更偏执,请使用cron脚本将文件(并重命名)移动到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.

解决方案

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:

  1. Make the file name and path not easily guessable. If a user has a path to getfile.php?file=1.txt they can readily infer that there is a 2.txt as well. Crypt the name or make it unsequenced.
  2. Make any script that serves up files affirm things such as the logged in user, authorization to the resource and strip anything from the file name containing a path to avoid rogue references to /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 or chown 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.

这篇关于如何允许PHP在不损害服务器安全性的情况下写入文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 08:57