How to hide images in a directory using PHP

You can keep images hidden on your server by placing this .htaccess file in the directory with the images.

hideimageshtaccess

This .htaccess file only allows scripts on the same server to access images in the directory, i.e. people will not be able to access these images from their browsers.

You can then create a php file that allows certain images to be served to browsers only allowing  certain images to be viewed.

Here’s an example of a PHP script that only allows ‘jpg’ files to be viewed.

<?PHP
$file=$_GET[‘file’];
header(“Content-type: image/jpg”);
if(strrchr($file, “.”) == “.jpg”){
readfile(“uploads/”.$file);
}
?>

‘uploads/’ is the directory the images and the .htaccess file are in and so the PHP script would be in the root directory.

Let’s pretend the PHP script is called readimages.php, you can reference it using standard html like this.

<img src=”http://mywebsite/readimages.php?file=logo.jpg”&gt;

If the image file ‘logo’ exists in the folder ‘upoads’ and it has the file extension ‘.jpg’ it will be served to the browser.

Advertisements

Published by

angelo bonavera

Hi I'm a web developer and I run a web hosting company called 2slick.com.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s