在 Ubuntu 上使用 PHP 写入文件时遇到问题 [英] Having trouble writing to a file with PHP on Ubuntu

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

问题描述

我在 Ubuntu 14.04 上运行 PHP 5.5.9.我在写入文件时遇到问题.我觉得这一定是文件权限问题,因为我很确定代码是正确的.我登录的用户有权在我尝试写入的文件夹中写入,但我不确定本地主机是否可以.我不确定 localhost 用户的名称是什么才能使用 chmod.我尝试使用 chmod 777 -R/var/www/html 并且脚本仍然无法写入我的目标文件夹,其路径为 /var/www/html/Projects/MD_ScrapingTool/files.这是我的代码:

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

推荐答案

经过更多的研究,我已经弄清楚了.以下是任何遇到相同问题的人的解决方案:

由于 localhost 属于 www-data 组,我只是将我的用户添加到该组.

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

然后,我授予 www-data 组写入权限.

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天全站免登陆