Detect if PHP file directly loaded
I'm using some PHP pages do some AJAX stuff but I don't want them to be directly accessible. Facebook does a similar thing so for example: domain.com/ajax/my_ajax_form.php
If I was to load that page using AJAX it would work fine, but if a user were to try and loading the file directly by typing in that url it would do through an error so e.g.
开发者_如何学Cif( IS FILE LOADED DIRECT? )
{
header ( HTTP/1.0 404 );
}
This isn't possible. You cannot rely on $_SERVER['HTTP_X_REQUESTED_WITH']
, and even if you could, it doesn't matter. Anyone can send the same request to your server that your browser does, via POST
or GET
.
What you should do is validate the request, and return the proper result if it is valid. If it is invalid, do not return a 404. (Browsers can cache errors like 404. If your client-side code had a trouble, subsequent requests may fail!) If the request is invalid, return an error of some sort.
Again, it is impossible to secure stuff like this. You should be validating the session and request data. That's all.
You can look for the HTTP_X_REQUESTED_WITH
header.
$is_ajax = array_key_exists('HTTP_X_REQUESTED_WITH', $_SERVER)
&& $_SERVER['HTTP_X_REQUESTED_WITH'] === 'XMLHttpRequest';
if (! $is_ajax) {
die('go away.');
}
Note, though, that it's not standard, but needs to be set explicitly on the requesting side. AFAIK, at least jQuery and Mootools set it though, probably most others as well, but don't take my word for it.
Simplest way is to only access that page via POST
, and not via GET
. Though keep in mind - if a browser can do it - then a hacker can too.
You have to use session variables, or more generally, cookies.
With cookies: (set in JavaScript)
- JavaScript: Set token in cookie
- JavaScript: Make XMLHttpRequest
- Server side: Check token from cookie
- Server side: Return JSON output or error message
Please note that this is no way secure! This just prevents easy linking.
With session variables: (cookies set in server side)
- Server side: Authenticate user, set privileges
- JavaScript: Make XMLHttpRequest
- Server side: Check privileges
- Server side: Return JSON output or error message
This method is as secure as the user authentication is.
精彩评论