Home  >  Article  >  Backend Development  >  PHP+Referer realizes image hotlink prevention! (Attached with example code)

PHP+Referer realizes image hotlink prevention! (Attached with example code)

藏色散人
藏色散人forward
2022-11-21 17:25:502045browse

This article will introduce to you the issues related to anti-hotlinking in PHP. The main content is to explain the Referer principle and the implementation method of image anti-hotlinking. I hope it will be helpful to friends in need~

1 , Picture anti-hotlinking

In some large websites, such as Baidu Tieba, the pictures on this site adopt anti-hotlinking rules, so that using the following code will cause errors. [Recommended: PHP Video Tutorial]

Simple code:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title></title>
  <link rel="stylesheet" href="">
</head>
<body>
  <!--引用一张百度贴吧的图片-->
  <img  src="http://imgsrc.baidu.com/forum/pic/item/03a4462309f79052204229be04f3d7ca7acbd5d5.jpg"/ alt="PHP+Referer realizes image hotlink prevention! (Attached with example code)" >
</body>
</html>

Problems:

PHP+Referer realizes image hotlink prevention! (Attached with example code)

The reason for the error

The main reason is that the pictures on this site adopt anti-hotlinking rules. In fact, this rule is relatively simple. You will know it once I tell you. The main reason is that the site knows that there is a request. When , it will first judge the information in the request header. If there is Referer information in the request header, it will then judge whether the Referer header information meets the requirements according to its own rules. The Referer information is the source address of the requested image.

Request header information in the browser:

(1) Normally use Baidu Tieba to view the request header information of the picture

PHP+Referer realizes image hotlink prevention! (Attached with example code)

(2 ) The header information of my code

PHP+Referer realizes image hotlink prevention! (Attached with example code)

I believe readers will understand after seeing this, why my code cannot access the image, but displays a warning for hotlinking For pictures, because our Referer header information is different from that of Baidu Tieba, when my request is sent, the site checks the Referer header information. When it sees that the source is not this site, it redirects to another picture.

Configure image anti-hotlinking for your own site:

(1) Enable the mod_rewrite module in the web server

#LoadModule rewrite_module modules/mod_rewrite.so, //replace the preceding Remove the # and then restart the server

(2) In the website or directory that needs to be protected against theft, write the .htaccess file and specify the anti-leeching rules

Steps:

Create a .htaccess file, use the save as method in windows to create a new file
Find the manual, use regular rules to judge in the .htaccess file

Specify the rule:

If it is If the image resource and the referer header information comes from this site, then the rewrite rules through

are as follows:

Assuming that my server is localhost, the meaning of the rule is that if the request is for image resources, But if the request source is not this site, it will be redirected to a no.png picture in the current directory.

RewriteEngine On
RewriteCond %{SCRIPT_FILENAME} .*\.(jpg|jpeg|png| gif) [NC]
RewriteCond %{HTTP_REFERER} !localhost [NC]
RewriteRule .* no.png

Access from localhost:

PHP+Referer realizes image hotlink prevention! (Attached with example code)

Visits from other sites:

PHP+Referer realizes image hotlink prevention! (Attached with example code)

At this point, we have finished learning about anti-leeching, but don’t worry, since it is a request header, of course it can be forged Yes, let’s talk about the anti-hotlinking rules below.

2. Anti-hotlinking

#My server is configured with image anti-hotlinking. Now we will use it to explain anti-hotlinking. If we When collecting pictures, we can forge a Referer header when collecting pictures when encountering sites that use anti-hotlinking technology.

The code below downloads a picture from a site configured with picture anti-hotlinking.

<?php
/**
 * 下载图片
 * @author webbc
 */
require &#39;./Http.class.php&#39;;//这个类是我自己封装的一个用于HTTp请求的类
$http = new Http("http://localhost/booledu/http/apple.jpg");
//$http->setHeader(&#39;Referer:http://tieba.baidu.com/&#39;);//设置referer头
$res = $http->get();
$content = strstr($res,"\r\n\r\n");
file_put_contents(&#39;./toutupian.jpg&#39;,substr($content,4));
echo "ok";
?>

The result of downloading without Referer header information:

PHP+Referer realizes image hotlink prevention! (Attached with example code)

The result of downloading with Referer header information:

PHP+Referer realizes image hotlink prevention! (Attached with example code)

Correspondingly, when you see this, you should be able to see how to prevent hotlinking. In fact, it is to add a Referer header information. So, where do you find the Referer header information for each site? This should be figured out through packet capture and analysis!

3. Encapsulated Http request class

<?php
/**
 * Http请求类
 * @author webbc
 */
class Http{
  const CRTF = "\r\n";
  private $errno = -1;
  private $errstr = &#39;&#39;;
  private $timeout = 5;
  private $url = null;//解析后的url数组
  private $version = &#39;HTTP/1.1&#39;;//http版本
  private $requestLine = array();//请求行信息
  private $header = array();//请求头信息
  private $body = array();//请求实体信息
  private $fh = null;//连接端口后返回的资源
  private $response = &#39;&#39;;//返回的结果
  //构造函数
  public function __construct($url){
    $this->connect($url);
    $this->setHeader(&#39;Host:&#39;.$this->url[&#39;host&#39;]);//设置头信息
  }
  //通过URL进行连接
  public function connect($url){
    $this->url = parse_url($url);//解析url
    if(!isset($this->url[&#39;port&#39;])){
      $this->url[&#39;port&#39;] = 80;
    }
    $this->fh = fsockopen($this->url[&#39;host&#39;],$this->url[&#39;port&#39;],$this->errno,$this->errstr,$this->timeout);
  }
  //设置请求行信息
  public function setRequestLine($method){
    $this->requestLine[0] = $method.&#39; &#39;.$this->url[&#39;path&#39;].&#39; &#39;.$this->version;
  }
  //设置请求头信息
  public function setHeader($headerLine){
    $this->header[] = $headerLine;
  }
  //设置请求实体信息
  public function setBody($body){
    $this->body[] = http_build_query($body);
  }
  //发送get请求
  public function get(){
    $this->setRequestLine(&#39;GET&#39;);//设置请求行
    $this->request();//发送请求
    $this->close();//关闭连接
    return $this->response;
  }
  //发送请求
  private function request(){
    //拼接请求的全部信息
    $reqestArr = array_merge($this->requestLine,$this->header,array(&#39;&#39;),$this->body,array(&#39;&#39;));
    $req = implode(self::CRTF,$reqestArr);
    //print_r($req);die;
    fwrite($this->fh,$req);//写入信息
    //读取
    while(!feof($this->fh)){
      $this->response .= fread($this->fh,1024);
    }
  }
  //发送post请求
  public function post($body = array()){
    //设置请求行
    $this->setRequestLine("POST");
    //设置实体信息
    $this->setBody($body);
    //设置Content-Type
    $this->setHeader(&#39;Content-Type:application/x-www-form-urlencoded&#39;);
    //设置Content-Length
    $this->setHeader(&#39;Content-Length:&#39;.strlen($this->body[0]));
    //请求
    $this->request();
    $this->close();//关闭连接
    return $this->response;
  }
  //关闭连接
  public function close(){
    fclose($this->fh);
  }
}
//测试get
// $http = new Http("http://news.163.com/16/0915/10/C10ES2HA00014PRF.html");
// $result = $http->get();
// echo $result;
//测试post
/*set_time_limit(0);
$str = &#39;abcdefghijklmnopqrstuvwxyz0123456789&#39;;
while(true){
  $http = new Http("http://211.70.176.138/yjhx/message.php");
  $str = str_shuffle($str);
  $username = substr($str,0,5);
  $email = substr($str,5,10).&#39;@qq.com&#39;;
  $content = substr($str,10);
  $message = "发表";
  $http->post(array(&#39;username&#39;=>$username,&#39;email&#39;=>$email,&#39;content&#39;=>$content,&#39;message&#39;=>$message));
  //sleep(0.1);
}*/
?>

The above is the detailed content of PHP+Referer realizes image hotlink prevention! (Attached with example code). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:jb51.net. If there is any infringement, please contact admin@php.cn delete