0

I have a PHP file: index.php at the root of my web directory (something along the lines of):

<?php 
  echo '<div>
    <img src="images/test.png">
  </div>';
?>

And I have a .htaccess file in the 'images/' directory which contains the following:

deny from all

As I understand it, this should allow <img src="images/test.png"> to be displayed on the webpage but should not allow a user to access the test.png file directly as follows: www.example.com/images/test.png (I expect this to throw a forbidden error or something along these lines).

Unfortunately, the above leads to the image not displaying on index.php as well as the image not displaying via direct url: www.example.com/images/test.png. If I remove the .htaccess file, the image displays fine, but it can be accessed by direct URL.

Any ideas why this would not be working as expected?

dw1991
  • 51
  • 1
  • 5
  • 1
    If the image can be loaded in the browser on a website, it can be accessed directly as well. Setting `deny from all` strangely enough denies everyone access. – adeneo May 17 '15 at 20:22
  • @adeneo from other posts I've looked at on SO - which strangely enough, are trying to achieve the same functionality as described in my post - the above .htaccess script works fine. That is, using deny from all stops the file from being loaded directly yet allows it to be accessed via the php file. As far as I am aware, this is expected functionality when using deny from all? – dw1991 May 17 '15 at 20:26
  • @adeneo Example of what I'm meaning: http://stackoverflow.com/questions/9282124/deny-direct-access-to-a-folder-and-file-by-htaccess – dw1991 May 17 '15 at 20:29
  • Oh yes, it can be accessed ***from PHP on the serverside***, but that's not the same as **loaded in the browser on the clientside** ! – adeneo May 17 '15 at 20:31
  • Ah ok, I guess that makes sense. Is there any other way to achieve the desired functionality where the file can be loaded on the client side but not accessed directly? Or is this somewhat of a pipe-dream? – dw1991 May 17 '15 at 20:36

1 Answers1

1

Yo/u are missing the big distinction between blocking access to an included php file (which is handled on the server side) and to an image which is referenced by php. The closest I can think of as an easy solution is to have your php file open the image and return it as an image.

Something like:

<?php 
  //Do whatever checking you want
  $im = file_get_contents("images/example.png");
  header("Content-type: image/jpeg");
  echo $im;  
  ?>

Note that this still allows someone who knows the name of the php file to get the image etc; all this is doing is giving you a place to do checking in php code (example of check would be http_referer checking if you wanted to block people from "hot-linking" images)

Foon
  • 6,148
  • 11
  • 40
  • 42