Search code examples
phpapache2file-permissionsubuntu-20.04

How to only allow PHP to download images from my server?


I have a server that contains a simple php file for downloading images and a folder containing those images.

<?php

$filepath = "myFiles/" . $_POST["file"];
if (file_exists($filepath)) {
    $file = fopen($filepath,"r") or die();
    echo fread($file,filesize($filepath));
    fclose($file);
}

?>

This download.php file as well as the myFiles folder are both located in the www/html/ folder.

I am trying to figure out a way to make it so that my PHP script can access my image files, while keeping the files locked away from regular visitors. My problem is that if I set permissions that the files can't be viewed through the browser, then the PHP script can't access them either. So either both have access or neither does.

Am I on the correct track? How could I make it so that I can download my images using a PHP script while keeping the images otherwise inaccessible?


Solution

  • That won't be something you can handle using the linux file system permissions. You can put back the linux permissions to what they were initially for the files.

    Instead, if you have a /home folder, I would recommend putting the original files to hide there. Check with your webhost if you have one.

    Otherwise, if you have to put everything in www absolutely, then put the files to hide in a new subfolder, e.g. "hidden-files", and in that folder put a .htaccess file inside to block direct browser access to the files. The .htaccess file can be a one-line file with Deny From All command inside.

    This way your files will only be able to be proxied through download.php.