1

How to make php script called by XMLHttpRequest (ajax) secure.

I mean, to not let PHP file functional by direct url, only by calling by script from my page (i don't want to show database results to not logged users, and called php script file have included database logins and functions).

I study and find unusable:

  • If i lock file folder by .htaccess or use Mod rewrite (not working properly at all and it is not recommended)

  • Header redirection not work (exactly i don't know URL or domain from which will be script called) if(@isset($_SERVER['HTTP_REFERER']) && $_SERVER['HTTP_REFERER']=="http://xxxxxxx.com/index.php?")

  • lastone not working is to include in php script ($_SERVER['HTTP_X_REQUESTED_WITH']) returns NULL: if($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest') { header('HTTP/1.1 403 Forbidden'); exit; };
Martin
  • 2,575
  • 6
  • 32
  • 53

1 Answers1

2

What about using randomized tokens? See best practice to generate random token for forgot password for example. You'll want to read up lots of articles on SO tho, there's much to consider when using tokens. (Especially looking at their security.)

Community
  • 1
  • 1
Fabian Schneider
  • 345
  • 2
  • 10
  • Okay how to effective ask token value in a script? I can send that value by GET or POST to the PHP script, but how i ask token from server to compare if is matching? Is it only solution, dos not sexist simple best practised way to unable run script outside logged envirovment? – Martin Feb 11 '14 at 11:11
  • 1
    This really depends on what exactly you're trying to achieve. From my understanding of your questions, you have users that are signed in. Thus you could really just have a quick signed check on your script. If you want it to be able to be accessed purely by your script, then you'll want to go with the tokens. Create a randomized token at page call, then add it via post/get to your ajax call, check for that exact token (you can save it in a session) and remove it directly after execution. – Fabian Schneider Feb 11 '14 at 11:14