php判断是否是ajax请求
为了程序安全上的考虑,我们在某些情况下会需要检测一个请求是否是 AJAX 请求,该如何去判断呢?本文就简要分享一下经验。
1. 使用原生 JavaScript 发出 ajax 请求时,我们可以给请求头部添加信息,以方便后端php程序进行区分,方法如下:
var xmlhttp=new XMLHttpRequest(); xmlhttp.open("GET","test.php",true); xmlhttp.setRequestHeader("X-Requested-With","XMLHttpRequest"); xmlhttp.send();
这里我们给头部添加了 X_REQUESTED_WITH 信息,值为 XMLHttpRequest,当然这里的值是可以随意设置的,比如:www.phpernote.com。这样在接收端 php 程序里面就可以这样写:
<?php // php 判断是否为 ajax 请求 if(isset($_SERVER['HTTP_X_REQUESTED_WITH'])&&strtolower($_SERVER['HTTP_X_REQUESTED_WITH'])=='xmlhttprequest'){ // ajax 请求的处理方式 }else{ // 正常请求的处理方式 }
2. 目前比较流行的js框架jquery就考虑的比较充分,jQuery 发出 ajax 请求时,会在请求头部添加一个名为 X-Requested-With 的信息,信息内容为:XMLHttpRequest,所以后端 php 同样可以用如上代码来进行判断。
注意:如果你的jquery请求是通过iframe打开网页的,那么HTTP_X_REQUESTED_WITH参数不会被传递,也就是说你没有办法判断请求的类型。
您可能感兴趣的文章
- php如何判断当前的操作系统是linux还是windows
- PHP判断一个请求是AJAX请求还是普通请求
- php判断字符串是否全英文,纯中文,中英文组合的方法
- PHP判断服务器SSL是否启用,也就是判断是否支持HTTPS连接
- php判断远程文件是否存在的办法
- php get_headers 判断URL是否有效
- PHP如何判断一个gif图片是否为动态图片(动画)
- php如何判断一个常量是否已经定义

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

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

Dreamweaver Mac version
Visual web development tools

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.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

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