阻止直接访问PHP文件,除了从AJAX请求? [英] Block direct access to PHP file except from AJAX request?

查看:269
本文介绍了阻止直接访问PHP文件,除了从AJAX请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望有一个使用AJAX来访问 ./ AJAX / file.ajax.php

I wish to have a webpage that uses AJAX to access a PHP file in ./ajax/file.ajax.php

但问题是,我不希望人们能够在浏览器输入地址直接访问PHP文件。

Trouble is, I don't want people to be able to type the address in their browser to access that PHP file directly.

有没有一种方法,我可以让这个只有AJAX请求可以访问文件?

Is there a way I can make it so that only AJAX requests can access the file?

有什么我可以在PHP文件检查实现这一目标?

Is there something I can check for in the PHP file to achieve this?

推荐答案

如果您正在使用jQuery做XHR,它将设置自定义标题 X-要求 - 以。您可以检查这一点,决定如何满足你的回应。

If you're using jQuery to make the XHR, it will set a custom header X-Requested-With. You can check for that and determine how to serve your response.

$isXhr = isset($_SERVER["HTTP_X_REQUESTED_WITH"])
         AND strotlower($_SERVER["HTTP_X_REQUESTED_WITH"]) == "xmlhttprequest";

不过,这是微不足道的恶搞。在过去,我用这个来决定是否呈现一整页(如果未设置)或页面片段(如果设置,将注入到当前页面)。

However, this is trivial to spoof. In the past, I've used this to decide whether to render a whole page (if not set) or a page fragment (if set, to be injected into current page).

这篇关于阻止直接访问PHP文件,除了从AJAX请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆