Prevent opening image in browser directly

前端 未结 1 656
北海茫月
北海茫月 2021-01-16 15:27

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 t

相关标签:
1条回答
  • 2021-01-16 15:53

    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)

    0 讨论(0)
提交回复
热议问题