Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent Direct Access To File Called By ajax Function [duplicate]

Tags:

ajax

php

I'm calling the php code from ajax like this:

ajaxRequest.open("GET", "func.php" + queryString, true);

Since it's a get request anyone can see it by simply examining the headers. The data being passed is not sensitive, but it could potentially be abused since it is also trivial to get the parameter names.

How do I prevent direct access to http://mysite/func.php yet allow my ajax page access to it?

Also I have tried the solution posted here but its doesn't work for me - always get the 'Direct access not premitted' message.

like image 834
jriggs Avatar asked Nov 18 '09 14:11

jriggs


3 Answers

Most Ajax requests/frameworks should set this particular header that you can use to filter Ajax v Non-ajax requests. I use this to help determine response type (json/html) in plenty of projects:

if( isset( $_SERVER['HTTP_X_REQUESTED_WITH'] ) && ( $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest' ) )
{
    // allow access....
} else {
    // ignore....
} 

edit: You can add this yourself in your own Ajax requests with the following in your javascript code:

var xhrobj = new XMLHttpRequest();
xhrobj.setRequestHeader("X-Requested-With", "XMLHttpRequest"); 
like image 128
Ian Van Ness Avatar answered Nov 19 '22 15:11

Ian Van Ness


what I use is: PHP sessions + a hash that is sent each time I do a request. This hash is generated using some algorithm in the server side

like image 36
Gabriel Sosa Avatar answered Nov 19 '22 17:11

Gabriel Sosa


Mmm... you could generate a one-time password on session start, which you could store in the _SESSION, and add a parameter to your ajax call which would re-transmit this (something like a captcha). It would be valid for that session only.

This would shield you from automated attacks, but a human who has access to your site could still do this manually, but it could be the base to devise something more complicated.

like image 8
Palantir Avatar answered Nov 19 '22 15:11

Palantir