Page 1 of 1

Securing scripts meant to be used with Ajax

Posted: Fri Apr 24, 2009 6:54 am
by Sindarin
I usually put this line on the top of the php scripts which I don't want directly accessed, like contact form validation/sending etc.

Code: Select all

if ('mypage.php' == basename($_SERVER['SCRIPT_FILENAME']))
{echo "Direct Access Denied.";exit;}
I want to use some functions of these php scripts I want to request with ajax (jQuery). If I place the above code in those scripts, the ajax request will return "Direct Access Denied.", so I need to remove it. This means someone could access these scripts directly from now on (as he can also see the filename in the page source). How can I fix this? Is there a method to tell if the page was requested via ajax?

On another note can someone use include()/require() to include a php script from my server to his own or request it via ajax? If yes, how can I fix this?

Re: Securing scripts meant to be used with Ajax

Posted: Fri Apr 24, 2009 12:07 pm
by kaisellgren
Sindarin wrote:I usually put this line on the top of the php scripts
I think it's better this way:

Code: Select all

if (!defined('IN_MY_SCRIPT')) exit;
Sindarin wrote:This means someone could access these scripts directly from now on
"AJAX" files can be always accessed directly.
Sindarin wrote:Is there a method to tell if the page was requested via ajax?
Not really.
Sindarin wrote:On another note can someone use include()/require() to include a php script from my server to his own or request it via ajax? If yes, how can I fix this?
I'm not sure what you mean by this. Why would this be for any harm? He cannot access your PHP code if that is what you thought... he can include the output (HTML usually or JSON) on his server, which does not do any harm to you.

"AJAX" files are just like other files on your server that are being requested directly. Make sure you have proper input/output filtering in place and so forth. Just remember that even if your AJAX calls do something, they can end up malicious when your server receives them if the user altered them in anyway. Therefore it is crucial to take all input seriously.