PHP code for anti hotlinking - php

In our sites we are doing a image protection section. So as a part of image protection we need
provide antihotlinking for images.In our site we are showing the image using a generated url.
For example in our site the image source is like: image_file.php?type=image&w=10&h=10&i=12
(this only a fake url for example purpose).
So using this url we need to show image in our site and at the same time want to prevent it from hot linking is there any way for prevent hotlinking?

If you can utilize the .htaccess method then great, additionally, as I said in my comment, a 100% fool proof way is to utilize base64 encoding. When you are displaying images, you can use this code to convert them to base64:
<?php
$imagedata = file_get_contents("/path/to/image.png");
$base64 = base64_encode($imagedata);
?>
<img src="data:image/jpeg;base64,<?= $base64; ?>" />
Also, if you want to get really creative, you can "RAT" the hotlink "thieves" out by displaying an alternative image using your .htaccess file... do this like so:
RewriteEngine on
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http://(www\.)?mydomain.com/.*$ [NC]
RewriteRule \.(gif|jpg|png)$ http://www.mydomain.com/dontstealmystuff.png [R,L]
just make sure dontstealmystuff.png is available on the server

basic .htaccess example
RewriteEngine on
RewriteCond %{HTTP_REFERER} !^$
RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?yourdomain.com [NC]
RewriteRule \.(jpg|jpeg|png|gif)$ - [NC,F,L]
above allows a blank REFERER (like me).
this does not:
RewriteEngine on
RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?yourdomain.com [NC]
RewriteRule \.(jpg|jpeg|png|gif)$ - [NC,F,L]
there are quite a few variations you can find, may need to play around a bit to find what is best for you.

Image hotlinking is usually detected by referer, but it won't work when:
user has turned off referer sending in his browser (I have this for privacy purposes)
page is viewed via HTTPS (browser shouldn't send referer data).
You'll block your actual users from viewing images.
Consider using sessions / cookies when dealing with this problem. You'll have to pass every image via php script then.

Generally speaking the proper way to do this is in something like an .htaccess file with a command such as:
RewriteEngine On
RewriteCond %{HTTP_REFERER} !^http://(.+\.)?somesite\.com/ [NC]
RewriteCond %{HTTP_REFERER} !^$
RewriteRule .*\.(jpe?g|gif|bmp|png)$ http://i.imgur.com/aNbhd.jpg [L]
However to do this in PHP it's basically the same. All you do is verify that $_SERVER['HTTP_REFERER'] starts with the URL for the page. However it's possible to spoof the HTTP_REFERER so it's not going to be 100%. However the user has to do this (an external site pretty (mostly...) much can't spoof this), so it will prevent other sites from embeding your images without placing your site in an iframe or some other hoopla.
Another way, and probably the safest though it's going to be the hardest on the server, is to use the $_SESSION variable to pass a token/flag around, then check the token.
session_start();
$_SESSION["allow_images"] = true;
Then on the PHP page that gets the image for them:
if($_SESSION["allow_images"])
{
//Send some pics!
}
However this only works if the user hasn't been to your site recently enough to not have their own session still active.

You can try checking the value of $_SERVER['HTTP_REFERER'] against a known value, but as the documentation states, that can be spoofed. It might help against the common case, though.

in image_file.php use http_referer for this.
$ref = isset($_SERVER['HTTP_REFERER'])? $_SERVER['HTTP_REFERER']: "";
if ($ref != "" && strpos($ref,'http://www.yourdomain.com/')===0)
{
//the request for this image is coming from some other domain, so take appropriate action
}
else
{
//do whatever logic you are currently using to show the images
}
Find a full-blown solution here: http://safalra.com/programming/php/prevent-hotlinking/

Related

Redirect specific Url variables

My site used to generate URLs like this:
/data.php?s=1432862823&type=basic
I have modified the program so the new URLs generated are:
/d.php?s=1432862823&t=basic
Since some people have bookmarked the old URLs I want to write a Rewrite rule that will get them to the new url.
I've not this so far:
RewriteEngine on
RewriteRule "^/data\.php$" "/d.php"
but I can't figure out how to account for the variables.
Try this :
RewriteEngine On
RewriteCond %{QUERY_STRING} ^s=([^&]+)&type=([^&]+) [NC]
RewriteRule ^data.php$ /d.php?s=%1&t=%2 [NC,R,L]
This will externally redirect a request for :
/data.php?s=foo&type=bar
to
/d.php?s=foo&t=bar
Edit: I do apologise, I only noticed now that you have changed the type parameter to t. As such, this solution will not fit your needs, unless for a URI where the query string parameters do not change. I'm leaving this answer here so that others may learn from it - you'll be surprised how many people don't know that the query string is automatically transferred to the new destination. Starkeen's answer, therefore, is the correct answer.
You could follow Starkeen's solution, which specifically checks for the query string and explicitly adds it to d.php. Alternatively, for simplicity, you could just use this:
RewriteEngine on
RewriteRule ^data.php$ /d.php [R=302,L]
The query string will automatically be transferred from data.php to d.php, and you will be redirected accordingly.
To make the redirect permanent and cached by browsers and search engines, change 302 to 301.

REFERER using .htaccess

I have php files that i do not want users to be directly access by typing in the URL, therefore I have hidden these using .htaccess. However I want the user to be passed on (referred) to the next php file once they have logged in.
e.g. 123.456.789:8080/one.php is the login page and the user will then be sent to 123.456.789:8080/two.php.
Below is an example of some code that i found on here, but have not been able to make it work for my variables, and the fact I have the IP address and port no. Thanks
RewriteEngine On
RewriteCond %{HTTP_REFERER} !^http://(www\.)?site\.com/ [NC]
RewriteRule (^|/)B\.php(/|$) - [F,NC]
If you are using php for the logon can you not use something like this?
if( $logged_in){
header("Location: http://somesite/two.php");
}

hide incoming querystring with htaccess

I want that anybody who comes to my site
site.com?affiliate=a12b345c67
hides the affiliate querystring completely
I'm sure it's something like this, but nothing happens
RewriteRule ^/?affiliate= / [L,R=301]
To strip affiliate= query string from your URLs, place this rule in your DOCUMENT_ROOT/.htaccess file:
RewriteEngine On
RewriteCond %{QUERY_STRING} ^affiliate=[^&]+ [NC]
RewriteRule ^ %{REQUEST_URI}? [L,R=301,NE]
First of all you need to charge the URL from which users are coming to your website. Change it to:
site.com?/a12b345c67/
.htaccess cant change your URL structure on the fly.
Let me know if its ok.
Regards.
you could save the incoming $_GET parameter(if exists) to a session(or cookie, or whatever persistent storage) and reload the page.
session_start();
if(isset($_GET['affiliate']){
$_SESSION['affiliate'] = $_GET['affiliate'];
header('location: site.com');
}
you could then use the affiliate token from the session,cookie or whatever persistent storage

Php - Is it possible to block access to a webpage depending on the address used?

Consider the following scenario.
There is a site on a local network which can be accessed one of 2 ways:
11.11.11.111/testsite (ip)
test.site.com (vhost)
Is it possible with php to only allow access using test.site.com?
EDIT:
While there were many good suggestions as to how to solve this problem, I went with Publi Design & John V.'s mod_rewrite suggestion, but I implemented it in the httpd.conf file and redirected to a forbidden page.
What worked for me was:
RewriteEngine On
RewriteCond %{HTTP_HOST} !^test.site.com$ [NC]
RewriteRule .? - [F]
I would avoid the PHP request and go up one level. I haven't tried this, but maybe the .htaccess file could help you, using something similar to this:
RewriteEngine On
RewriteCond %{HTTP_HOST} !^11.11.11.111/testsite$ [NC]
RewriteRule ^(.*)$ test.site.com/$1 [L,R=301]
You might have to play around with it, but I would imagine something along those lines should get you to where you want to be.
As Michael P suggested in his comment, it's best to do this using a server configuration file, rather than with PHP. But it is possible with PHP, and rather easy. All you need is a simple if/else statement using PHP's global variable $_SERVER. Something like this should do.
<?php
// put this at the top of every page that will be accessed
if ($_SERVER['HTTP_HOST'] != 'test.test.com') { 'Please visit this site using the correct link: http://test.test.com'; exit; }
?>

How can I remove file extension from a website address?

I am designing a website. I want my website address to look like the following image:
I don't want my website to look like http://something.example/profile.php.
I want the .php extension to be removed in the address bar when someone opens my website. In other words, I want my website to be like: http://something.example/profile
As a second example, you can look at the Stack Overflow website address itself.
How can I get this done?
Just add an .htaccess file to the root folder of your site (for example, /home/domains/domain.example/htdocs/) with the following content:
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php
More about how this works in these pages: mod_rewrite guide (introduction, using it), reference documentation
First, verify that the mod_rewrite module is installed. Then, be careful to understand how it works, many people get it backwards.
You don't hide URLs or extensions. What you do is create a NEW URL that directs to the old one, for example
The URL to put on your web site will be yoursite.example/play?m=asdf
or better yet
yoursite.example/asdf
Even though the directory asdf doesn't exist. Then with mod_rewrite installed you put this in .htaccess. Basically it says, if the requested URL is NOT a file and is NOT a directory, direct it to my script:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /play.php [L]
Almost done - now you just have to write some stuff into your PHP script to parse out the new URL. You want to do this so that the OLD ones work too - what you do is maintain a system by which the variable is always exactly the same OR create a database table that correlates the "SEO friendly URL" with the product id. An example might be
/Some-Cool-Video (which equals product ID asdf)
The advantage to this? Search engines will index the keywords "Some Cool Video." asdf? Who's going to search for that?
I can't give you specifics of how to program this, but take the query string, strip off the end
yoursite.example/Some-Cool-Video
turns into "asdf"
Then set the m variable to m=asdf.
So both URLs will still go to the same product
yoursite.example/play.php?m=asdf
yoursite.example/Some-Cool-Video
mod_rewrite can do lots of other important stuff too, Google for it and get it activated on your server (it's probably already installed.)
You have different choices.
One on them is creating a folder named "profile" and rename your "profile.php" to "default.php" and put it into "profile" folder.
and you can give orders to this page in this way:
Old page: http://something.example/profile.php?id=a&abc=1
New page: http://something.example/profile/?id=a&abc=1
If you are not satisfied leave a comment for complicated methods.
Here is a simple PHP way that I use.
If a page is requested with the .php extension then a new request is made without the .php extension. The .php extension is then no longer shown in the browser's address field.
I came up with this solution because none of the many .htaccess suggestions worked for me and it was quicker to implement this in PHP than trying to find out why the .htaccess did not work on my server.
Put this at the beginning of each PHP file (preferrably before anything else):
include_once('scripts.php');
strip_php_extension();
Then put these functions in the file 'scripts.php':
//==== Strip .php extension from requested URI
function strip_php_extension()
{
$uri = $_SERVER['REQUEST_URI'];
$ext = substr(strrchr($uri, '.'), 1);
if ($ext == 'php')
{
$url = substr($uri, 0, strrpos($uri, '.'));
redirect($url);
}
}
//==== Redirect. Try PHP header redirect, then Java, then http redirect
function redirect($url)
{
if (!headers_sent())
{
/* If headers not yet sent => do php redirect */
header('Location: '.$url);
exit;
}
else
{
/* If headers already sent => do javaScript redirect */
echo '<script type="text/javascript">';
echo 'window.location.href="'.$url.'";';
echo '</script>';
/* If javaScript is disabled => do html redirect */
echo '<noscript>';
echo '<meta http-equiv="refresh" content="0; url='.$url.'" />';
echo '</noscript>';
exit;
}
}
Obviously you still need to have setup Apache to redirect any request without extension to the file with the extension.
The above solution simply checks if the requested URI has an extension, if it does it requests the URI without the extension. Then Apache does the redirect to the file with the extension, but only the requested URI (without the extension) is shown in the browser's address field.
The advantage is that all your "href" links in your code can still have the full filename, i.e. including the .php extension.
The problem with creating a directory and keeping index.php in it is that
your links with menu will stop functioning
There will be way too many directories. For eg, there will be a seperate directory for each and every question here on stackoverflow
The solutions are
1. MOD REWRITE (as suggested above)
2. use a php code to dynamically include other files in index file. Read a bit more abt it here http://inobscuro.com/tutorials/read/16/
Actually, the simplest way to manipulate this is to
Open a new folder on your server, e.g. "Data"
Put index.php (or index.html) in it
And then the URL www.yoursite.example/data will read that index.php file. If you want to take it further, open a subfolder (e.g. "List") in it, put another index.php in that folder and you can have www.yoursite.example/data/list run that PHP file.
This way you can have full control over this, very useful for SEO.
same as Igor but should work without line 2:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.php [NC,L]
Tony, your script is ok, but if you have 100 files? Need add this code in all these :
include_once('scripts.php');
strip_php_extension();
I think you include a menu in each php file (probably your menu is showed in all your web pages), so you can add these 2 lines of code only in your menu file. This work for me :D
Remove a file extension through .htaccess:
Original URL: http://ravinderrathore.herobo.com/contact.php
.htaccess rule to remove .php, .html, etc. file extensions from URLs:
RewriteRule ^(.*)$ $1.php
After Rewriting: http://ravinderrathore.herobo.com/contact
RewriteEngine on
RewriteCond %{THE_REQUEST} ^(.+)\.php([#?][^\ ]*)?\ HTTP/
RewriteRule ^index(.*)?$ index.php$1 [L,QSA]
RewriteRule ^login_success(/)?$ login_success.php [L,QSA]
RewriteRule ^contact(/)?$ contact.php [L,QSA]
just nearly the same with the first answer about, but some more advantage.
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.html -f
RewriteRule ^(.*)$ $1.html
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php
Just add up if you have a other file-extension in your sites
For those who are still looking for a simple answer to this; You can remove your file extension by using .htaccessbut this solution is just saving the day maybe even not. Because when user copies the URL from address bar or tries to reload or even coming back from history, your standart Apache Router will not be able to realize what are you looking for and throw you a 404 Error. You need a dedicated Router for this purpose to make your app understand what does the URL actually means by saying something Server and File System has no idea about.
I leave here my solution for this. This is tested and used many times for my clients and for my projects too. It supports multi language and language detection too. Read Readme file is recommended. It also provides you a good structure to have a tidy project with differenciated language files (you can even have different designs for each language) and separated css,js and phpfiles even more like images or whatever you have.
Cr8Router - Simple PHP Router

Categories