php - .htaccess deny from all stops access on website

283

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 thetest.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 onindex.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?

635

Answer

Solution:

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)

People are also looking for solutions to the problem: php - Looping result from select statement throws error

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.