Everytime I use file_put_contents
in my PHP script on DigitalOcean's LAMP server, I get this error message:
file_put_contents(test_digitalocean.json): failed to open stream:
Permission denied in /var/www/html/test_digitalocean.php
How can I properly set permissions?
I access my scripts by entering the server's IP address followed by /test_digitalocean.php
into the browser.
All scripts are uploaded to /var/www/html/
If I look at www folder from FileZilla, I can see that the permissions are 775 with the owner and group both as www-data.
Your web server needs to have write permissions on the file. Apache on any linux system runs as some particular user. You can find out which user by putting this script on your server and accessing it:
<?php
passthru("whoami");
On Debian/Ubuntu, this user is www-data. So the directory or file you'd want to write would need to have write privileges granted to that group. These commands might be useful, but will require root or sudo privileges:
sudo chgrp www-data /path/to/file.json
sudo chmod 664 /path/to/file.json
Or, if you want to grant write access to a directory where you might upload many files, try this:
sudo chgrp www-data /path/to/directory
sudo chmod 775 /path/to/directory
I would NOT run that command on your /var/www/html directory if you can help it. It's generally a bad idea security-wise to grant apache write permissions inside your web root.