Home >Backend Development >PHP Tutorial >PHP anti-hotlink implementation

PHP anti-hotlink implementation

WBOY
WBOYOriginal
2016-07-29 08:50:531205browse

Sometimes we hope that users who visit our website can only enter our website through specific links or pages. In this case, we need to implement anti-hotlink technology. This uses the referer content filtering in the http protocol.

For example, we have a local web page with the path: http://localhost/http/fdl_one.php and the content is as follows:

<a href="fdl_two.php">click here to see more</a>
There is another web page with the path: http://localhost/http/fdl_three.php , the contents are as follows:
<a href="fdl_two.php">I also want to see more</a>
The pages that these two web pages want to access, namely http://localhost/http/fdl_two.php, can be accessed separately. But if you want to filter out access to fdl_three.php, that is, you can only enter fdl_two.php through the hyperlink of fdl_one.php. The content in fdl_two.php can be as follows:
<?php
	if(isset($_SERVER[&#39;HTTP_REFERER&#39;])){
		if(strpos($_SERVER[&#39;HTTP_REFERER&#39;],"http://localhost/http/fdl_one.php")===FALSE){
			header("Location:http_test_err.php");
		}else{
			echo "yes,you can see it now.";
		}
	}else{
		header("Location:http_test_err.php");//如果用户不是通过链接点击,此时不会有referer,跳转到禁止访问提示页面
	}
	
?>

http_test_err.php stores prohibited access information.

It is worth mentioning the return value of strpos. Returns the starting position of parameter 2 string that exists in parameter 1 string. If parameter 2 is not found, FALSE is returned. Therefore, when using it, you should first determine whether it matches. At this time, you should strictly control the type and value of the return value and use the === symbol. (Because the return value may be 0 when matching!!)

What is more widely used in real use is that a certain page can be accessed through its own site, but cannot be accessed through other sites. At this time, you only need to modify the content of parameter 2 in the strpos function and change it to the directory name of your own site. You can filter out other visits.


The above introduces the implementation of anti-hotlinking in PHP, including anti-hotlinking and PHP content. I hope it will be helpful to friends who are interested in PHP tutorials.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn