Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent direct access to a PHP page

Tags:

ajax

php

apache

How do I prevent my users from accessing directly pages meant for ajax calls only?

Passing a key during ajax call seems like a solution, whereas access without the key will not be processed. But it is also easy to fabricate the key, no? Curse of View Source...

p/s: Using Apache as webserver.

EDIT: To answer why, I have jQuery ui-tabs in my index.php, and inside those tabs are forms with scripts, which won't work if they're accessed directly. Why a user would want to do that, I don't know, I just figure I'd be more user friendly by preventing direct access to forms without validation scripts.

like image 444
syaz Avatar asked Oct 09 '08 00:10

syaz


2 Answers

There is no way of guaranteeing that they're accessing it through AJAX. Both direct access and AJAX access come from the client, so it can easily be faked.

Why do you want to do this anyways?

If it's because the PHP code isn't very secure, make the PHP code more secure. (For example, if your AJAX passes the user id to the PHP file, write code in the PHP file to make sure that is the correct user id.)

like image 132
Paige Ruten Avatar answered Oct 01 '22 21:10

Paige Ruten


As others have said, Ajax request can be emulated be creating the proper headers. If you want to have a basic check to see if the request is an Ajax request you can use:

 if($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest') {
     //Request identified as ajax request
 }

However you should never base your security on this check. It will eliminate direct accesses to the page if that is what you need.

like image 29
Eran Galperin Avatar answered Oct 01 '22 22:10

Eran Galperin