Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Having trouble writing to a file with PHP on Ubuntu

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.";
}
like image 751
beznez Avatar asked Jul 01 '14 14:07

beznez


People also ask

Where do I write PHP code in Ubuntu?

php file inside /var/www/html directory.

Can PHP write to file?

PHP Write to File - fwrite()The fwrite() function is used to write to a file. The first parameter of fwrite() contains the name of the file to write to and the second parameter is the string to be written.

Where do I put PHP files in Linux?

Run Your PHP File in XAMPP When you install the XAMPP software, it creates the htdocs directory, which is the document root of your default web server domain: localhost. So if you go to http://localhost/example.php, the server will try to find the example. php file under the htdocs directory.


1 Answers

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!

like image 151
beznez Avatar answered Oct 10 '22 06:10

beznez