如何检测如果文件正在被访问或请求? [英] How to detect if file is being accessed or requested?
问题描述
AI有一个PHP文件,如果用户直接访问它,他应该被重定向到另一个位置,但如果我的脚本,通过Ajax调用它,它应该做的没有什么特别的。
A I have a PHP file that if the user access it directly he should be redirected to another location, but if my script call it through ajax, it should do nothing special.
例如,如果用户访问
/site/page.php
他应该被重定向到
/index.php?view=page
但如果他是在的index.php?认为=页
文件应加载没有重定向。
But if he is on the index.php?view=page
the file should load without redirects.
我怎么能这样做?
推荐答案
修改:如果您想确定是否通过JavaScript或没有请求的脚本,你必须以某种信号吧。
EDIT: If you want to determine if a script was requested through Javascript or not, you'll have to signal it somehow.
若干工具包定义标题 X-要求 - 以
。在这种情况下,您可以检查的JavaScript调用带:
Several toolkits define the header X-Requested-With
. In that case, you can check for a Javascript call with:
if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) &&
strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
//requested with Javascript
}
您可以检查由 debug_backtrace
。
You can check the size of the result given by debug_backtrace
.
或者(更好的),你可以检查 $ _ SERVER ['SCRIPT_FILENAME']
:
Alternatively (better), you can check $_SERVER['SCRIPT_FILENAME']
:
if (realpath(__FILE__) == realpath($_SERVER['SCRIPT_FILENAME'])) {
//this one was requested; not in include
}
这篇关于如何检测如果文件正在被访问或请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!