Prevent opening image in browser directly

2019-02-20 01:36发布

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条回答
我命由我不由天
2楼-- · 2019-02-20 01:57

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)

查看更多
登录 后发表回答