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

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

Alexander Ross

Alexander Ross

Gaming, Esports & Interactive Media Writer

Alexander Ross has covered the video game industry for a decade, writing deep dives on game design, esports tournaments, VR developments, and gaming culture.

Share this article
Twitter Facebook Pinterest