无法在Ubuntu上使用PHP写入文件 [英] Having trouble writing to a file with PHP on Ubuntu

查看:128
本文介绍了无法在Ubuntu上使用PHP写入文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Ubuntu 14.04上运行PHP 5.5.9。我无法写入文件。我觉得这必须是一个文件权限问题,因为我敢肯定代码是正确的。我登录的用户有权写入我想要写入的文件夹,但我不确定本地主机是否可以。我不确定本地用户的名字是为了使用 chmod 。我尝试使用 chmod 777 -R / var / www / html ,脚本仍然无法写入到我的目标文件夹,其路径的/ var / www / html等/项目/ MD_ScrapingTool /文件。这是我的代码:

  $ file ='filetest.txt'; 
if($ handle = fopen($ file,'w')){
$ content =123\\\
456;
fwrite($ handle,$ content);
fclose($ handle);
} else {
echo无法打开写入文件。


解决方案

已经知道了。以下是解决任何有同样问题的人:


因为localhost属于 www-data 组,所以我刚添加了我的

  sudo usermod -a -G www-data my_username 


$ b 然后,我将文件夹添加到组中。

  sudo chgrp -R www-data / var / www 

然后,我给写权限www-data group。

  sudo chmod -R g + w / var / www 

这对我没有任何其他问题。谢谢!


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.";
}

解决方案

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!

这篇关于无法在Ubuntu上使用PHP写入文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆