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

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

Nov 21, 2022 pm 05:25 PM
referer Picture hotlink protection

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="/static/imghw/default1.png"  data-src="http://imgsrc.baidu.com/forum/pic/item/03a4462309f79052204229be04f3d7ca7acbd5d5.jpg"  class="lazy"  / alt="PHP+Referer realizes image hotlink prevention! (Attached with example code)" >
</body>
</html>
Copy after login

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";
?>
Copy after login

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);
}*/
?>
Copy after login

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 of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

cURL in PHP: How to Use the PHP cURL Extension in REST APIs cURL in PHP: How to Use the PHP cURL Extension in REST APIs Mar 14, 2025 am 11:42 AM

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

Explain the concept of late static binding in PHP. Explain the concept of late static binding in PHP. Mar 21, 2025 pm 01:33 PM

Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Framework Security Features: Protecting against vulnerabilities. Framework Security Features: Protecting against vulnerabilities. Mar 28, 2025 pm 05:11 PM

Article discusses essential security features in frameworks to protect against vulnerabilities, including input validation, authentication, and regular updates.

How to send a POST request containing JSON data using PHP's cURL library? How to send a POST request containing JSON data using PHP's cURL library? Apr 01, 2025 pm 03:12 PM

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...

Customizing/Extending Frameworks: How to add custom functionality. Customizing/Extending Frameworks: How to add custom functionality. Mar 28, 2025 pm 05:12 PM

The article discusses adding custom functionality to frameworks, focusing on understanding architecture, identifying extension points, and best practices for integration and debugging.

What exactly is the non-blocking feature of ReactPHP? How to handle its blocking I/O operations? What exactly is the non-blocking feature of ReactPHP? How to handle its blocking I/O operations? Apr 01, 2025 pm 03:09 PM

An official introduction to the non-blocking feature of ReactPHP in-depth interpretation of ReactPHP's non-blocking feature has aroused many developers' questions: "ReactPHPisnon-blockingbydefault...

See all articles