user2720360
user2720360

Reputation: 251

How can I block direct access to images in a directory but allow PHP to display them?

I'm using a .htaccess file with the following code:

Order deny, allow
Deny from all
Allow from localhost

But when I display the images I'm just putting a link to the image in an tag, but the images are not showing up.

How can I display the image but disallow direct access to it? Is there a way for me to just copy the raw bytes of the file and display them?

Upvotes: 2

Views: 4535

Answers (2)

Jimmy
Jimmy

Reputation: 553

Be sure to save embedded.png in same folder as this example source.

<?php
function data_uri($file, $mime) 
{  
  $contents = file_get_contents($file);
  $base64   = base64_encode($contents); 
  return ('data:' . $mime . ';base64,' . $base64);
}
?>

<html>
    <h1>Embedded Image:-</h1>
    <img src="<?php echo data_uri('embedded.png','image/png'); ?>" alt="Embedded image" />
</html>

Upvotes: 9

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798616

Send the appropriate Content-Type header for the image, and then use readfile() to stream the bytes to output.

Also, if you're going to use a filepath in the URL for this, be certain to sanitize the filepath first so that e.g. /etc/passwd can't be read using your script.

Upvotes: 0

Related Questions