Friday, January 26, 2024

[SOLVED] PHP chmod and file_get_content permission problem

Issue

In PHP, I'm grabbing remote images with:

$img = file_get_contents("http://example.com/image.jpg");
file_put_contents("../testdir/photo.jpg",$img);

I get a Permission Denied error unless testdir is set to chmod 0777. Which, I tried to do with PHP and then set it back to 0755:

chmod("../testdir/", 0777);
$img = file_get_contents("http://example.com/image.jpg");
file_put_contents("../testdir/photo.jpg",$img);
chmod("../testdir/", 0755);

but I got Operation Not Permitted Is there a safe, working alternative?

Thanks!


Solution

Change the owner of the directory to be the user which PHP will be running as (typically the same user the web server process - Apache, lighttpd, nginx, whatever - is running as). Then you won't get permission errors.



Answered By - Amber
Answer Checked By - Pedro (WPSolving Volunteer)