faqts : Computers : Programming : Languages : PHP : Common Problems : Images

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

1 of 3 people (33%) answered Yes
Recently 1 of 3 people (33%) answered Yes

Entry

How do I prevent user access to my images but allow my php scripts to display the images?

Feb 26th, 2005 18:04
Philip Olson, Frank Cicchetto,


This is somewhat impossible as all information sent to the browser is of
course read by the browser so users can get this information BUT so that
users won't know where the image files are located you can easily hide
that information. First, here's what the HTML will look like:
<img src="something.php">
This way, something.php will output the image file information for you.
For example, something.php may look like so:
<?php
$image_name = 'someimage.jpg';
$ext        = substr($filename, strrpos($image_name, '.')+1);
$filename   = "images/$image_name";
if (is_readable($filename)) {
  header("Content-Type: image/$ext");
  header("Content-length: " . filesize($filename));
  readfile($filename);
}
?>
Whether $image_name is passed in through GET, is a random image, or
whatever, the above example will work but should be modified to suit
your needs. The main point is that header() is used to send the
appropriate header type and length, and the image is then outputted. The
directory (and perhaps name) of the image is hidden from the user.
Here's an example of passing information into the image script:
<img src="somefile.php?image_name=foo.jpg">
This way within the script above you would have something like:
$image_name = trim($_GET['image_name']);
Realize that people could then modify this so take special precautions.
Ideally you'll only allow image files, and not allow users to include
directories.
See also: http://php.net/header