Justin John
Justin John

Reputation: 9615

Secure files from direct access

I have hosted a site, the documents suggest to put files under folder public_html. I have three files index.php(view page), common.js, and result.php(php) in root folder. On clicking a button in index.php(view) file will trigger an ajax function to result.php.

The problem is everyone can access the result.php directly...

I trying to make folder structure, that all php files(result.php) are in folder behind root. So it will not accessed directly from browser using rewrite rule or anything else.

Please help me to solve this issue...

Upvotes: 0

Views: 224

Answers (3)

Sammaye
Sammaye

Reputation: 43884

To make a file only acccessible via ajax you can use:

public static function isAjax() {
    return (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH']=="XMLHttpRequest");
}

It returns true or false. Basically if it returns true then let the user carry on otherwise stop them.

Word of caution: Not all JS libraries/frameworks actually set this header but most do (JQuery, Mootools etc) and not all versions so make sure you have the latest version of a library/framework before you use this.

Plus if the user spoofs your headers then there is no real way to stop them.

I tend to use this as a precursor for stopping AJAX pages from being visible publicly. I also use parameter integrity checking and a random hash stored in session (CSRF type thing) to check if the user is legitamately accessing an AJAX page.

Upvotes: 2

Vatev
Vatev

Reputation: 7590

You can't protect it by moving it around, because there is no way to distinguish if a request to result.php was triggered by a legitimate AJAX call from index.php except for a session (or some other type of token).
You need to use a php session (or something equivalent) to:

  1. Store what the use has access to (in index.php).
  2. Check if he has access to it in (result.php)

Upvotes: 1

williamvicary
williamvicary

Reputation: 805

You can't make a file accessible via ajax and then not accessible via the correct browser requests, as the Ajax call is doing the same behaviour a web-browser could.

Upvotes: 0

Related Questions