


PHP+Referer realizes image hotlink prevention! (Attached with example code)
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>
Problems:
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
(2 ) The header information of my 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:
Visits from other sites:
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 './Http.class.php';//这个类是我自己封装的一个用于HTTp请求的类 $http = new Http("http://localhost/booledu/http/apple.jpg"); //$http->setHeader('Referer:http://tieba.baidu.com/');//设置referer头 $res = $http->get(); $content = strstr($res,"\r\n\r\n"); file_put_contents('./toutupian.jpg',substr($content,4)); echo "ok"; ?>
The result of downloading without Referer header information:
The result of downloading with Referer header information:
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 = ''; private $timeout = 5; private $url = null;//解析后的url数组 private $version = 'HTTP/1.1';//http版本 private $requestLine = array();//请求行信息 private $header = array();//请求头信息 private $body = array();//请求实体信息 private $fh = null;//连接端口后返回的资源 private $response = '';//返回的结果 //构造函数 public function __construct($url){ $this->connect($url); $this->setHeader('Host:'.$this->url['host']);//设置头信息 } //通过URL进行连接 public function connect($url){ $this->url = parse_url($url);//解析url if(!isset($this->url['port'])){ $this->url['port'] = 80; } $this->fh = fsockopen($this->url['host'],$this->url['port'],$this->errno,$this->errstr,$this->timeout); } //设置请求行信息 public function setRequestLine($method){ $this->requestLine[0] = $method.' '.$this->url['path'].' '.$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('GET');//设置请求行 $this->request();//发送请求 $this->close();//关闭连接 return $this->response; } //发送请求 private function request(){ //拼接请求的全部信息 $reqestArr = array_merge($this->requestLine,$this->header,array(''),$this->body,array('')); $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('Content-Type:application/x-www-form-urlencoded'); //设置Content-Length $this->setHeader('Content-Length:'.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 = 'abcdefghijklmnopqrstuvwxyz0123456789'; 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).'@qq.com'; $content = substr($str,10); $message = "发表"; $http->post(array('username'=>$username,'email'=>$email,'content'=>$content,'message'=>$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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



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.

Alipay PHP...

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

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,

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

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�...

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

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...
