How to securely allow a PHP script to save files?

I have a PHP script that is supposed to save images to /var/www/backend/images/ folder. The script is in /var/www/html/save_image.php

The owner and the group of all the folders and files in /var/www/ is ubuntu.

For testing, this is my simple script that won't work:

<?php
$myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
$txt = "John Doe\n";
fwrite($myfile, $txt);
$txt = "Jane Doe\n";
fwrite($myfile, $txt);
fclose($myfile);
?>

And I get the following message:

Warning: fopen(newfile.txt): failed to open stream: Permission denied in /var/www/html/save_image.php on line 2 Unable to open file!

How can I allow this script only to save files?

12

1 Answer

The Apache service is typically run from the www-data account so, unless you intentionally changed it, you will need to do this:

sudo chown -R www-data:www-data /var/www
1

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like