Prevent opening image in browser directly

风格不统一 提交于 2019-12-01 09:53:42

问题


I have a folder with pictures 1.jpg, 2.jpg, 3.jpg... Is there any way to prevent user to type the URL like www.example.com/pictures/3.jpg directly into browser and loading that image?

The image should be loaded if web html calls it (< img href=...).

Is that possible to do? Using IIS URL Rewrite or some other technique?

I am using IIS7.5. My goal is to prevent users to see the next image... I know, I could have names encoded, but I have some old database that goes from 1-1000 and I'd somehow like to prevent just users not to browse using url with no refferer... Because every day I am serving one picture and I don't want that they find the rest...

Is that possible at all?


回答1:


You can try it with a url rewrite by relying on HTTP_REFERRER but that's not always accurate and could possibly block users on some browsers from seeing the images on your site as well.

If I were you I would move all of your images outside your web directory (or preferably just block the pictures folder altogether) and then build a php script like this called image.php:

<?php

define('NUM_IMAGES', 1000);

header('Content-Type: image/png');

$image = imagecreatefromjpeg('pictures/'.((int)(time()/86400)%NUM_IMAGES+1).'.jpg');
imagepng($image);

?>

The script above will output an image to the users browser which will change once a day to the next image in sequence and you can use it like: <img src="image.php" />

Then, since your images folder is blocked, nobody can see any other image. Then can still request image.php directly but they'll only see the image of the day.

If you don't want to rotate automatically once a day and want manual control over which image it shows you can also just replace the '.((int)(time()/86400)%1000+1).' with the number of the image you want to display .

If you do want it to rotate automatically, but want to control the time it updates at you can add an offset to time() like: ((time()+$offset)/86400)



来源:https://stackoverflow.com/questions/6809376/prevent-opening-image-in-browser-directly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!