使用 PHP 打开或创建文件时权限被拒绝

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9200557/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 06:20:17  来源:igfitidea点击:

Permission denied when opening or creating files with PHP

phpfile-ioftpfile-permissions

提问by Kalle Jillheden

I can't create files with php, because the file dosent got permission for that. I get this error:

我无法用 php 创建文件,因为文件没有获得许可。我收到此错误:

Warning: fopen(test.txt): failed to open stream: Permission denied in /web/com/example.com/index.php on line 20
Warning: fwrite() expects parameter 1 to be resource, boolean given in /web/com/example.com/index.php on line 21
Warning: fclose() expects parameter 1 to be resource, boolean given in /web/com/example.com/index.php on line 22

警告:fopen(test.txt):无法打开流:第 20 行 /web/com/example.com/index.php 中的权限被拒绝
警告:fwrite() 期望参数 1 为资源,布尔值在 /web/ 中给出com/example.com/index.php 第 21 行
警告:fclose() 期望参数 1 为资源,布尔值在第 22 行 /web/com/example.com/index.php 中给出

This is the code I was using:

这是我使用的代码:

<?php
 $file = fopen("test.txt","w");
 echo fwrite($file,"Hello World. Testing!");
 fclose($file);
 ?> 

Simple as that! This is example code from w3schools.

就那么简单!这是来自 w3schools 的示例代码

So I need help to find out how to give the file the needed permissions. I'm uploading files to my site with the net2ftpFTP web application, if it matters.

所以我需要帮助来找出如何为文件提供所需的权限。如果重要的话,我正在使用net2ftpFTP Web 应用程序将文件上传到我的站点。

回答by Garry Welding

The folder your PHP script is trying to write to will probably be owned by the root user. Your PHP script is more than likely running under the www-data user if you're using a default Ubuntu/Apache/PHP setup.

您的 PHP 脚本尝试写入的文件夹可能由 root 用户拥有。如果您使用默认的 Ubuntu/Apache/PHP 设置,您的 PHP 脚本很可能在 www-data 用户下运行。

As such you need to:

因此,您需要:

chown -R www-data:www-data folder
chmod -R g+w folder

If you find PHP is running under a user that is different from www-data then just change the user a group in the first line of code.

如果您发现 PHP 在与 www-data 不同的用户下运行,则只需在第一行代码中将用户更改为组。

PS. change "folder" for your actual folder name.

附注。将“文件夹”更改为您的实际文件夹名称。

回答by Ryan P

The user running PHP (usually the apache user) doesn't have write permission on the folder the script is running in. Try using an absolute path, like "/tmp/test.txt" -- tmp is usually writable by any user, but the contents tend to be wiped out on reboot.

运行 PHP 的用户(通常是 apache 用户)对运行脚本的文件夹没有写权限。尝试使用绝对路径,如“/tmp/test.txt”——tmp 通常可由任何用户写入,但内容往往会在重新启动时被清除。