I am using .htaccess rule to prevent image directory access directly. here is .htaccess code
Deny from all
and i placed this .htaccess file to image directory.
problem is when i try to access some of the images in webpage it is giving me failed to load image error or you can say image not exist.
<img class="highlight-right wow animated" src="/img/spark.png" height="192" width="48" alt="">
i want to deny access for people accessing it directly but at least it should work on webpage.
Any advise on this.
Edit: I tried this rule
RewriteCond %{HTTP_REFERER} !^http://(www\.)?localhost/ [NC]
RewriteRule \.(jpe?g|gif|bmp|png)$ - [F,NC]
and
RewriteEngine on
RewriteCond %{HTTP_REFERER} !^http://(www\.)?localhost [NC]
RewriteCond %{HTTP_REFERER} !^http://(www\.)?localhost.*$ [NC]
RewriteRule \.(gif|jpg|png)$ - [F]
But both are not working as images are not showing on the webpage.
You could set your .htaccess
to block them based on the referrer as follows:
RewriteEngine on
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?yoursite.com [NC]
RewriteRule \.(jpg|png|gif)$ http://yoursite.com/errorImage.jpg [NC,R,L]
Note that the HTTP_REFERER
isn't reliable as it can be changed in the client's browser but it's the simplest and most efficient method available.
A more robust method would require the use of cookies or sessions, but that would increase the server load and therefore reduce the response time.
i want to deny access for people accessing it directly but at least it should work on webpage.
1. In .htaccess
use Deny from all
rule to block all direct access.
2. Change your image source links to refer to a PHP script in charge of returning the right image.
<img src="/path/to/images.php?f=spark.png">
Notice how I passed the image name in a parameter? That's how PHP will know which image is requested. In images.php do:
$IMG_DIR = '/path/to/images'; //put all protected images here
$img = $_GET['f']; //the file's name, matches the f= parameter in <img>
$img_path = $IMG_DIR."/$img";
if(!is_file($img_path)){ // make sure this image exists
http_response_code(404); //404 not found error
exit;
}
$extension = pathinfo($img,PATHINFO_EXTENSION); //eg: "png"
$mimetype = "image/$extension"; //type of image. browser needs this info
$size = filesize($img_path);
//tell the browser what to expect
header("Content-Type: $mimetype");
header("Content-Length: $size");
//send the file to the browser
readfile($img_path);
I don't do it here but this approach allows you to restrict access as you wish. You could for instance test whether a user is logged in by looking at $_SESSION
contents before you decide whether to return the image.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.