1

I'm uploading images to a public 'uploads' folder, renaming the files to the ID of the file's entry in a MySQL table. So, because the IDs are in increasing order, anyone can download/view the images (some of which are supposed to be accessible only by some specific people). But I don't want anyone to be able to access the files by entering the URL.

One approach for this would be to upload the images somewhere other than the public directory, and then using each image's base64 code in the PHP script for the output. But this would increase the page load time.

What are alternatives to this problem? One would be to produce a hash using the crypt() function and rename the file, storing the file's name in a table.

Umang Galaiya
  • 534
  • 5
  • 11
  • Put the images in a private folder, then write a php script that outputs the image. You can pass this script an ID that's not guessable. You can see an example here: http://stackoverflow.com/questions/1851849/output-an-image-in-php – Telmo Marques Dec 03 '14 at 14:43
  • Put images out of www root and write handler which will serve them setting proper header and checking rights. – Aleksei Matiushkin Dec 03 '14 at 14:43
  • Best way would be to load the images in PHP using and then output it using the image header. – Peter Dec 03 '14 at 14:44

1 Answers1

3

The hash option is probably best. Store the images by their DB id somewhere OUTSIDE of your document root, to prevent direct access. Then your image viewing script would have something like:

<?php
$hash = $_GET['id'];
$info = get_image_metadata_from_database($hash); // look up ID, mime type, etc..
if ($info === false) {
    readfile('/path/to/image/with/errortext.jpg'); // invalid hash, non-existent img, etc...
}
header('Content-type: ' . $info['mime']);
readfile('/path/to/image/storage/ . $info['filename']);

Since presumably this script would be used as a target for <img> tags, you can't output a standard error message for invalid hashes - that'd just show up as a broken image in the client, So output a standard "oops, something went wrong" picture instead.

Marc B
  • 356,200
  • 43
  • 426
  • 500
  • This alone will increase your traffic, as no caching can kick in. Implementing HTTP header detection and a proper response should help - that's the downside of wanting to "protect" your pictures. – AmigoJack Dec 03 '14 at 15:25
  • The users will be able to download the images once the page is loaded, right? I need them to be able to download images from the page. – Umang Galaiya Dec 03 '14 at 19:20