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

2022-01-09 00:00:00 file-io ftp file-permissions php

我不能用 php 创建文件,因为文件 dosent 获得了许可.我收到此错误:

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

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

这是我使用的代码:

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

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

所以我需要帮助来了解如何为文件授予所需的权限.我正在使用 net2ftp FTP Web 应用程序将文件上传到我的网站,如果有必要的话.

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

推荐答案

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

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.

因此,您需要:

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

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

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.

PS.将文件夹"更改为您的实际文件夹名称.

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

相关文章