Alex
Alex

Reputation: 104

I want to prevent other users to access images directly in my Yii application.

I have this user directory that contains all my user's profile pictures. When I use the image tag, it points to that user directory. If someone wants to access that image using the direct link, they can. I want to prevent them from being able to access an image directly. Can I use the asset Manager in yii to make that happen or what I need is a totally different thing ?

Upvotes: 1

Views: 1418

Answers (2)

DAG
DAG

Reputation: 6994

This should do it and even allow visitors with no HTPP_REFERER:

RewriteEngine On
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?yourdomain.com [NC]
RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?yourotherdomain.com [NC]
RewriteRule ^path/to/user/(.+)?(jpg|jpeg|gif|png|tiff)$ http://yourdomain.com/do_not_hot_link.png [NC, R, L]

Just replace yourdomain.com with your domain and the last url with the "forbidden" page (requests are getting redirect to this!)

Upvotes: 1

claustrofob
claustrofob

Reputation: 4984

There are a lot of ways to implement it. And not sure if there is some build in functionality for that in Yii.

There are some easy ways to do it in .htaccess file.

The first approach checks HTTP_REFERER and if it does not much your domain shows 403 Forbidden page:

RewriteEngine  on   

RewriteBase  /

RewriteCond %{HTTP_REFERER} !your_domain
RewriteRule ^images - [F,L]

where your_domain is actually your domain name, and images is the user profile image folder.

There are some downsides in this like in HTTP_REFERER may not be sent by some clients or cut by proxy servers or firewalls.

Another way is to set some cookie in your app and then check it in .htaccess:

setcookie("show_img", 1, time()+3600, "/");

and then

RewriteEngine  on   

RewriteBase  /

RewriteCond %{HTTP_COOKIE} !show_img=([^;]+) [NC]
RewriteRule ^images - [F,L]

this approach actually does not prevent your visitors from viewing it using direct link. But it will definitely bring a lot of headache to webmasters who would like to insert images from your server.

Upvotes: 0

Related Questions