Reputation: 28783
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.
if( IS FILE LOADED DIRECT? )
{
header ( HTTP/1.0 404 );
}
Upvotes: 0
Views: 254
Reputation: 11
You have to use session variables, or more generally, cookies.
With cookies: (set in JavaScript)
Please note that this is no way secure! This just prevents easy linking.
With session variables: (cookies set in server side)
This method is as secure as the user authentication is.
Upvotes: 1
Reputation: 163272
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.
Upvotes: 5
Reputation: 16952
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.
Upvotes: 5
Reputation: 9007
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.
Upvotes: 2