Reputation: 2570
I have a bunch of helper files and parsers, some of which are called through AJAX. My understanding is that I can't use .htaccess to block access to those files as it will break AJAX. So my question is: is there actually any harm or danger in allowing direct access to those files? If so, how do I allow AJAX but block users from accessing them?
Upvotes: 0
Views: 133
Reputation: 69967
Ajax is users accessing them, just in a controlled manner.
If the scripts/files can be accessed from Ajax, you can't stop someone from accessing them directly. You can put roadblocks like looking for certain headers but people can and will find a way around that.
There is no harm or danger in allowing direct access to them as long as your code is secure :)
For example, if you're gonna have Ajax make a call like POST /message/delete?id=1
, you'd better make sure the caller has permission to delete the message with ID 1.
Filter and validate all input and put sufficient access checks in place and you should be about as safe as any other website on the internet.
Upvotes: 1
Reputation: 33813
To prevent users loading a php file directly in the browser but still allowing ajax requests through and also allowing the file to be included in the document you could try adding the following to the top of the script you wish to protect from direct access.
if ( realpath(__FILE__) == realpath( $_SERVER['SCRIPT_FILENAME'] ) ) {
header( 'HTTP/1.0 403 Forbidden', TRUE, 403 );
die( header( 'location:/403/error/Forbidden' ) );/* change to your error page url etc */
}
Upvotes: 0
Reputation: 434
You can use the php $_SERVER
value to validate the ajax requests but if the user use spoofing
its not work also if you have perfect validations in your php scripts don't worry about the direct access
if(isset( $_SERVER['HTTP_X_REQUESTED_WITH'] ) && ( $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest' ) )
{
//Your response
} else {
//I hate users redirect
}
Upvotes: 1