Having trouble writing to a file with PHP on Ubuntu

不想你离开。 提交于 2019-11-27 15:09:36

问题


I am running PHP 5.5.9 on Ubuntu 14.04. I'm having trouble writing to a file. I feel like this has to be a file permissions problem because I'm pretty sure the code is correct. The user that I'm logged in as has permissions to write in the folders that I am trying to write into, but I'm not sure if the localhost does. I'm not sure what the name of the localhost user is in order to use chmod. I tried using chmod 777 -R /var/www/html and the script is still is not able to write to my target folder, which has the path /var/www/html/Projects/MD_ScrapingTool/files. Here is my code:

$file = 'filetest.txt';
if($handle = fopen($file, 'w')) {
    $content = "123\n456";
    fwrite($handle, $content);
    fclose($handle);
} else {
    echo "Could not open file for writing.";
}

回答1:


After some more research, I've got it figured out. Here is the solution for anyone having the same problem:

Since localhost belongs to the www-data group, I just added my user to that group.

sudo usermod -a -G www-data my_username

Then, I added the folder to the group.

sudo chgrp -R www-data /var/www

Then, I gave write permissions to the www-data group.

sudo chmod -R g+w /var/www

This worked for me without any other issue. Thanks!




回答2:


You can verify that you have the permission on the folder '/html/Projects/MD_ScrapingTool/files/' and try with an absolute path.




回答3:


Try giving the absolute path and the filename with open:

$file = '/html/Projects/MD_ScrapingTool/files/filetest.txt';

If the file does not exist, fopen should create the file with 'w' mode.



来源:https://stackoverflow.com/questions/24512771/having-trouble-writing-to-a-file-with-php-on-ubuntu

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