search
HomeBackend DevelopmentPHP Tutorial有一个很难的问题,php获取javascript的值来判断域名来路,后期不好处理~

全部代码如下
首先你在浏览器中运行,打开控制台观察
http://localhost/test.php

<a href="test1.php">跳转到test1</a>

然后跳转到test1.php,代码
<?phpsession_start();require "./test2.php";class A{	function __construct()	{		$b=new B();		$b->judge();	}	function judge()	{		if($_SESSION['status']==1){			return true;			}else{			return false;			}	}	function run()	{		if($this->judge()){			echo 'success';			}else{			echo 'error';			}	}}$a=new A();$a->run();?>

作用是在执行A类方法的时候先判断域名来路,是否来自localhost,是的话,输出success,不是输出error
test2.php代码
<?phpsession_start();class B{	function judge()	{		echo '<script>		var xmlhttp;		if (window.ActiveXObject){		  xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");		}else{		  xmlhttp = new XMLHttpRequest();		}		xmlhttp.open("POST", "./test3.php", true);		xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");		xmlhttp.send("data="+document.referrer);		console.log(document.referrer); //控制台观察		xmlhttp.onreadystatechange = function(){		  if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {		  }		};</script>';	}}?>

test3.php,调用ajax执行文件
<?phpsession_start();if(stristr($_POST['data'], 'localhost')){    			$_SESSION['status']=1;    		}else{    			$_SESSION['status']='';    		}?>


回复讨论(解决方案)

难点就在于最后输出来的原码是

<script>		var xmlhttp;		if (window.ActiveXObject){		  xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");		}else{		  xmlhttp = new XMLHttpRequest();		}		xmlhttp.open("POST", "./test3.php", true);		xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");		xmlhttp.send("data="+document.referrer);		console.log(document.referrer);		xmlhttp.onreadystatechange = function(){		  if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {		  }		};</script>success

那么有人可能会有方法,用php缓存,其实我也试过了
session_start();
class B{
function judge()
{
               ob_start();//比如加在这里
echo '<script> <br /> var xmlhttp; <br /> if (window.ActiveXObject){ <br /> xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); <br /> }else{ <br /> xmlhttp = new XMLHttpRequest(); <br /> } <br /> xmlhttp.open("POST", "./test3.php", true); <br /> xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); <br /> xmlhttp.send("data="+document.referrer); <br /> console.log(document.referrer); <br /> xmlhttp.onreadystatechange = function(){ <br /> if (xmlhttp.readyState === 4 && xmlhttp.status === 200) { <br /> } <br /> };</script>';
              ob_clean()();//比如加在这里
}
}
?>
输出的结果的确是去掉了<script>脚本,但同时里面的语句如,console.log(document.referrer);也不会执行了 </script>

上面的代码忘记用代码格式括起来了,函数写法有误多了(),意思就是那样,我粘贴的时候弄错了
言归正传,大家有什么好的思路吗???

因为头部多了那一段javascript文件,我这里只是简单的输出了字符串,
如果调用html模版,
就会变成
<script>*********</script>
nbsp;html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

w3c声明头部有js代码会影响样式表现的

我能问一下你处理的问题是想要做什么,还是研究这个问题?因为我没看懂你要干什么,不好意思

说说你想想做什么?遇到了什么问题

说说你想想做什么?遇到了什么问题


这段函数的作用就是当执行一个类中方法的时候,先判断这个请求是不是来自于当前站点,如果是就执行,不是就不执行,
用来防止跨站请求攻击的。
本来打算使用$_SERVER['HTTP_REFERER']来做,但是这个服务端的参数是可以人为伪造的,只有本地的js代码里的
document.referrer才是安全的,所以用这个来判断

看不明白需求,
你都是PHP文件,如果要知道前一页面来源,用$_SERVER['HTTP_REFERER']就可以了,有必要这么麻烦搞JS吗

我能问一下你处理的问题是想要做什么,还是研究这个问题?因为我没看懂你要干什么,不好意思


可以算是技术研究,防止CSRF攻击,就是跨站请求伪造

而且我对调用AJAX执行的那段代码也没信心,正确的做法是ajax返回成功后才继续操作,
而我那样做可行性有待研究,
其实也可以不用按我的思路,
有什么好的方法来说说吧

整个请求都是可以伪造的
这样做确实会给伪造带来困难,但代码会变得很复杂...

可以变通一下,用cookie/session得到用户,得不到就报错。
如果用户请求太频繁就屏蔽请求。然后用缓存实现的话性能应该还可以。

Statement
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
How to make PHP applications fasterHow to make PHP applications fasterMay 12, 2025 am 12:12 AM

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

PHP Performance Optimization Checklist: Improve Speed NowPHP Performance Optimization Checklist: Improve Speed NowMay 12, 2025 am 12:07 AM

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

PHP Dependency Injection: Improve Code TestabilityPHP Dependency Injection: Improve Code TestabilityMay 12, 2025 am 12:03 AM

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

PHP Performance Optimization: Database Query OptimizationPHP Performance Optimization: Database Query OptimizationMay 12, 2025 am 12:02 AM

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

Simple Guide: Sending Email with PHP ScriptSimple Guide: Sending Email with PHP ScriptMay 12, 2025 am 12:02 AM

PHPisusedforsendingemailsduetoitsbuilt-inmail()functionandsupportivelibrarieslikePHPMailerandSwiftMailer.1)Usethemail()functionforbasicemails,butithaslimitations.2)EmployPHPMailerforadvancedfeatureslikeHTMLemailsandattachments.3)Improvedeliverability

PHP Performance: Identifying and Fixing BottlenecksPHP Performance: Identifying and Fixing BottlenecksMay 11, 2025 am 12:13 AM

PHP performance bottlenecks can be solved through the following steps: 1) Use Xdebug or Blackfire for performance analysis to find out the problem; 2) Optimize database queries and use caches, such as APCu; 3) Use efficient functions such as array_filter to optimize array operations; 4) Configure OPcache for bytecode cache; 5) Optimize the front-end, such as reducing HTTP requests and optimizing pictures; 6) Continuously monitor and optimize performance. Through these methods, the performance of PHP applications can be significantly improved.

Dependency Injection for PHP: a quick summaryDependency Injection for PHP: a quick summaryMay 11, 2025 am 12:09 AM

DependencyInjection(DI)inPHPisadesignpatternthatmanagesandreducesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itallowspassingdependencieslikedatabaseconnectionstoclassesasparameters,facilitatingeasiertestingandscalability.

Increase PHP Performance: Caching Strategies & TechniquesIncrease PHP Performance: Caching Strategies & TechniquesMay 11, 2025 am 12:08 AM

CachingimprovesPHPperformancebystoringresultsofcomputationsorqueriesforquickretrieval,reducingserverloadandenhancingresponsetimes.Effectivestrategiesinclude:1)Opcodecaching,whichstorescompiledPHPscriptsinmemorytoskipcompilation;2)DatacachingusingMemc

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

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

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.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Atom editor mac version download

Atom editor mac version download

The most popular open source editor