首页 > 开发 > Php > 正文

php验证请求页面来源

2020-06-09 12:51:24
字体:
来源:转载
供稿:网友

php验证请求页面来源:

  1. if$_server['http_x_requested_with'] == 'xmlhttprequest' ) { 
  2.     echo 'ajax'
  3. else { 
  4.     echo 'normal'

jquery内部实现ajax的时候,已经加入了标识,jquery源码中是这样的:

xhr.setrequestheader("x-requested-with", "xmlhttprequest");

所以,在php中可以通过http_x_requested_with来判断,不需要另外实现,下面看原理:在发送ajax请求的时候,我们可以通过xmlhttprequest这个对象,创建自定义的header头信息,如果您使用的是原生的ajax方法,也就是未使用jquery或者其他js框架包装的ajax方法,那么代码如下:

xmlhttprequest.setrequestheader("request_type","ajax");  

通过jquery的$.ajax()方法,可以轻松地在发送ajax请求之前,创建我们自定义的header头信息.

  1. $.ajax({ 
  2.         type: "get"
  3.         url: base_url + 
  4.  
  5. 'php_check_ajax_request/get_user_list.html'
  6.         beforesend: function (xmlhttprequest) { 
  7.             xmlhttprequest.setrequestheader("request_type","ajax"); 
  8.         }, 
  9.         success: function(data){ 
  10.                 $("#user_list").html(data); 
  11.                 $tip.hide(); 
  12.                 $button.attr('disabled',true); 
  13.         } 
  14. }); 

在php获取时:

  1. if (isset($_server['http_request_type']) && $_server['http_request_type'
  2. == "ajax"){//ajax提交 
  3. }else{//非ajax提交 

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表