search
HomeBackend DevelopmentPHP TutorialHow to use PHP to obtain referer and determine the source to prevent illegal access

This article will introduce to you how to use PHP to obtain the referer to determine the source to prevent illegal access? It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.

How to use PHP to obtain referer and determine the source to prevent illegal access

The php code of download page down.php Now I found that if I open it directly with Thunder or Google Chrome, the downloaded file can be output, and it has no anti-leeching effect at all. Now I want to allow only those connected to my own site to use it directly. Those connected to other sites and those who directly enter this address will jump to the copy.htm page.

The $_SERVER["HTTP_REFERER"] predefined server variable in PHP can determine the source.

$_SESSION['HTTP_REFERER'] can obtain the source address of the previous connection of the current link, that is, the URL address of the previous page linked to the current page.
It is generally used to determine where the viewer clicked the link to jump to this page, that is, the so-called origin. It can also be used to prevent hotlinking by determining the origin.
For example:

<?php
 $url_array = parse_url($_SESSION[&#39;HTTP_REFERER&#39;]); 
 //如果页面的域名不是服务器域名,就连接到登陆窗口 
 if($_SERVER[&#39;HTTP_HOST&#39;] != $url_array["host"]) { 
 header("location: login.php"); 
 exit; 
 } 
 ?>

Recently there is a project that needs to prevent users from illegally accessing a json page. The basic solution is to determine the source to restrict non-call access:

$_SERVER[‘HTTP_REFERER’]:来路链接,可能带尾巴(如: 
可以通过php内置函数parse_url()来获取到当前网址(www.httple.net),即:
$refererUrl = parse_url($_SERVER[‘HTTP_REFERER’]);
$host = $refererUrl[‘host’];
$host的值即为来路的网址(www.httple.net)。
获取到了来路的网址之后,我们就可以通过这个网址来限制访问该页面的权限了。代码如下:
if(!isset($_SERVER[‘HTTP_REFERER’]) || $referurl[‘host’] !=”www.httple.net”) { header(“location: /”); 
//如果没有来路,或者来路不是本站,跳转到首页。 exit; }

Putting this line of code at the top of the json data page can easily solve this problem.

Defects of this processing method: the normal data of the page can be obtained through forged sources.

Related code

The method of getting the source Url mainly uses the HTTP_REFERER function in the server variable. The code is pasted:

function get_referer(){   
$url = $_SERVER["HTTP_REFERER"]; //获取完整的来路URL   
$str = str_replace("http://","",$url); //去掉http://   
$strdomain = explode("/",$str); // 以“/”分开成数组   
$domain = $strdomain[0]; //取第一个“/”以前的字符  
return $domain;  
}   

//对于百度、谷歌搜索引擎来路判断   
function get_seo(){  
$s = 0;   
if(strstr(get_referer(),&#39;baidu.com&#39;)){   
$s = 1;   
}   
else if(strstr(get_referer(),&#39;google.com.hk&#39;)){   
$s = 1;   
}   
return $se;    
}

php website Get the source Url The method mainly uses the HTTP_REFERER function in the server variable. The code is pasted:

function get_referer(){
$url = $_SERVER["HTTP_REFERER"]; //获取完整的来路URL
$str = str_replace(“http://”,””,$url); //去掉http://
$strdomain = explode(“/”,$str); // 以“/”分开成数组
$domain = $strdomain[0]; //取第一个“/”以前的字符
return $domain;
}

//对于百度、谷歌搜索引擎来路判断
function get_seo(){
$s = 0;
if(strstr(get_referer(),’baidu.com’)){
$s = 1;
}
else if(strstr(get_referer(),’google.com.hk’)){
$s = 1;
}
return $se;
}

When processing a form, you have to consider Discuz has already judged the possibility of static submission by users based on formhash

Here I use another way to determine the origin of the page. Of course, this method can also be used to forge the origin of HTTP_REFERER

The second part is to solve the problem that header('location: in PHP cannot get HTTP_REFERER for the next page after jumping to the page. Here we can only add a link to the page and then use js to simulate clicking the link, so that the next page will definitely Received HTTP_REFERER. Keyword: document.getElementById('gourl').click();

Recommended learning: php video tutorial

The above is the detailed content of How to use PHP to obtain referer and determine the source to prevent illegal access. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:CSDN. If there is any infringement, please contact admin@php.cn delete
PHP Performance Tuning for High Traffic WebsitesPHP Performance Tuning for High Traffic WebsitesMay 14, 2025 am 12:13 AM

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

Dependency Injection in PHP: Code Examples for BeginnersDependency Injection in PHP: Code Examples for BeginnersMay 14, 2025 am 12:08 AM

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

PHP Performance: is it possible to optimize the application?PHP Performance: is it possible to optimize the application?May 14, 2025 am 12:04 AM

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

PHP Performance Optimization: The Ultimate GuidePHP Performance Optimization: The Ultimate GuideMay 14, 2025 am 12:02 AM

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

See all articles

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

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.