Maison >développement back-end >tutoriel php >php防止伪造数据从URL提交解决方法_PHP教程
php防止伪造的数据从URL提交方法。
针对伪造的数据从URL提交的情况,首先是一个检查前一页来源的如下代码:
<?<span>/*</span><span>PHP防止站外提交数据的方法</span><span>*/</span> <span>function</span><span> CheckURL(){ </span><span>$servername</span>=<span>$_SERVER</span>['SERVER_NAME'<span>]; </span><span>$sub_from</span>=<span>$_SERVER</span>["HTTP_REFERER"<span>]; </span><span>$sub_len</span>=<span>strlen</span>(<span>$servername</span><span>); </span><span>$checkfrom</span>=<span>substr</span>(<span>$sub_from</span>,7,<span>$sub_len</span><span>); </span><span>if</span>(<span>$checkfrom</span>!=<span>$servername</span>)<span>die</span>("警告!你正在从外部提交数据!请立即终止!"<span>); } </span>?>
这个方法只能防止手动在浏览栏上输入的URL。
事实上只要在服务器上构造出一个指向该URL的超链接(www.jbxue.com)比如在发贴时加入超链,再点击,这个Check就完全不起作用了。
目前觉得还是用POST的方法传递重要数据比较可靠。
可以在form中插入一些隐藏的text用于传递数据。
或者使用下面的方法,利用Ajax从客户端向服务器提交数据。
<span>/*</span><span>创建XHR对象</span><span>*/</span> <span>function</span><span> createXHR() { </span><span>if</span> (window.<span>XMLHttpRequest){ </span><span>var</span> oHttp = <span>new</span><span> XMLHttpRequest(); </span><span>return</span><span> oHttp; } // www.jbxue.com </span><span>else</span> <span>if</span> (window.<span>ActiveXObject){ </span><span>var</span> versions = ["MSXML2.XmlHttp.6.0","MSXML2.XmlHttp.3.0"<span>]; </span><span>for</span> (<span>var</span> i = 0; i < versions.length; i++<span>){ </span><span>try</span><span> { </span><span>var</span> oHttp = <span>new</span><span> ActiveXObject(versions[i]); </span><span>return</span><span> oHttp; } </span><span>catch</span><span> (error) {} } } </span><span>throw</span> <span>new</span> Error("你的浏览器不支持AJAX!"<span>); } </span><span>/*</span><span>用AJAX向page页面传递数据</span><span>*/</span> <span>function</span> ajaxPost(url,query_string=''<span>) { </span><span>var</span><span> xhr; xhr </span>=<span> createXHR(); xhr</span>.open('POST',url,<span>false</span><span>); xhr</span>.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=gb2312"<span>); xhr</span>.onreadystatechange = <span>function</span>(){<span>if</span> (xhr.readyState == 4)<span>if</span> (xhr.status != 200)<span>return</span><span>;} xhr</span>.<span>send(query_string); }</span>