Permission denied when opening or creating files with PHP

夙愿已清 提交于 2020-11-28 06:39:52

问题


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

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

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.

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.


回答1:


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.

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.

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




回答2:


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.



来源:https://stackoverflow.com/questions/9200557/permission-denied-when-opening-or-creating-files-with-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!