Securing scripts meant to be used with Ajax

Discussions of secure PHP coding. Security in software is important, so don't be afraid to ask. And when answering: be anal. Nitpick. No security vulnerability is too small.

Moderator: General Moderators

Post Reply
User avatar
Sindarin
Forum Regular
Posts: 521
Joined: Tue Sep 25, 2007 8:36 am
Location: Greece

Securing scripts meant to be used with Ajax

Post 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?
User avatar
kaisellgren
DevNet Resident
Posts: 1675
Joined: Sat Jan 07, 2006 5:52 am
Location: Lahti, Finland.

Re: Securing scripts meant to be used with Ajax

Post 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.
Post Reply