1

I let users upload images to a specified folder.

Now I want to show the images when they are accessed from the source code, but not via url. So nobody should be able to access the images via url, like domain.de/images/img1.jpg.... How can I do that?

nameless
  • 1,483
  • 5
  • 32
  • 78
  • This question maybe related [link]http://stackoverflow.com/questions/4286677/show-image-using-file-get-contents – Jason K Sep 08 '15 at 15:41
  • @JasonK edited my post, so it's more clear what I want. – nameless Sep 08 '15 at 15:43
  • This sounds like a job for Apache (or whatever web server you're using) rather than PHP. The key is to refuse access to the images if the referring URL isn't in your domain. – Simba Sep 08 '15 at 16:26

1 Answers1

1

Place the images in a directory whose content cannot be accessed directly via URL (in this case forbid access to images/)

When you have to serve one of them send the correct header for the image type, read the image from disk and send it to the client

header( 'Content-Type: image/jpeg' );
readfile( $pathToTheImage );
Paolo
  • 15,233
  • 27
  • 70
  • 91
  • Where do I have to place the source code you provided? And how can I prevent the folder from access? Just put it one level higher, then the other files? @Paolo – nameless Sep 08 '15 at 15:50
  • Ideally you would have an URL with a GET or POST parameter for displaying an image. Ex. `showImage.php?imgId=12345`. The script will validate the request and if ok serve the image. -- To prevent access to the images folder you can put it higher than the web server root folder or explicitly deny access in the web server configuration file (.htaccess for Apache) – Paolo Sep 08 '15 at 15:57
  • Okay, and how do I serve it? How can I tell the showImage.php file, where it should send the image and how can I access the image then in the file, where it was sent via header? – nameless Sep 08 '15 at 16:31
  • `readfile()` reads the file at the path specified as parameter (the content of variable `$pathToTheImage` in the example) and sends it to the client. See http://php.net/manual/en/function.readfile.php – Paolo Sep 08 '15 at 16:34
  • Okay, but when you say, it's sent to the client, then they download it, right? (like on the php.net example).. But I want to display it on the page it's sent to.. – nameless Sep 08 '15 at 16:37
  • You html page will have `` When the page is loaded then the browser will request the image calling the script. The script will serve the image and finally the browser will display the image on the page accordingly to the html code. – Paolo Sep 08 '15 at 16:41