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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 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)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1269
29
C# Tutorial
1248
24
PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Apr 17, 2025 am 12:06 AM

In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values ​​to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

How does PHP type hinting work, including scalar types, return types, union types, and nullable types? How does PHP type hinting work, including scalar types, return types, union types, and nullable types? Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

See all articles