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.
For example, if a user access
/site/page.php
he should be redirected to
/index.php?view=page
But if he is on the index.php?view=page
the file should load without redirects.
How can I do that?
EDIT: If you want to determine if a script was requested through Javascript or not, you'll have to signal it somehow.
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
}
You can check the size of the result given by debug_backtrace
.
Alternatively (better), you can check $_SERVER['SCRIPT_FILENAME']
:
if (realpath(__FILE__) == realpath($_SERVER['SCRIPT_FILENAME'])) {
//this one was requested; not in include
}
By "it should do nothing special" do you mean it shouldn't redirect?
So the Q is really if user accesses a URL for a PHP file directly, it should redirect, if thru AJAX, process as normal? (to really clarify, you mean thru a URL and not thru a include statement, right?)
Answer: You can't. Artefacto mentions the HTTP_X_REQUESTED_WITH header - sure, but that can be faked.
Is it really so bad is the user accesses the URL directly? If the answer is "OMG Yes!" then maybe there is something wrong with how the system is designed. Redesign it until the answer is "Actually, I suppose it wouldn't really hurt."
If you really don't want someone accessing /site/page.php
, you should consider moving /site/page.php
outside of your web root. Then make your index.php
load it as needed:
<?php
$includes = "/path/to/includes"; // specified in a config file somewhere
if ($_GET["view"] == "page") {
require_once(path_join($includes, "page.php"));
DoStuffInPageDotPHP();
}
else {
DoSomethingElse();
}
?>
精彩评论