I've quickly made a function to deny or allow access to files that are only used thru Ajax Calls.
Key Generator
/**
* Generate a key for file access permission
*
* Function that returns a key to grant access to a PHP file
* that will be consulted by an ajax call.
*
* @param str $salt Any given string to append to the session ID
*
* @return str Access Key
*/
public function file_access_key_generator($salt) {
return sha1(session_id() . $salt);
}
Key Validation
/**
* Match file access permission key
*
* Function to match the given key with the one generated.
*
* @param str $salt Any given string to append to the session ID
* @param str $key Key to match
*
* @return bollean
*/
public function file_access_key_check($salt, $key) {
return ($this->file_access_key_generator($salt) == $key) ? true : false;
}
The goal, as mentioned, is to prevent direct access to files that should only be accessed thru an Ajax Call within the application.
The methodology implemented is as follows:
// Generate the key to pass with the Ajax Post variables
$check = $this->my_class->file_access_key_generator(basename(__FILE__, '.php'));
// Validating the key
if (isset($_POST['check']) &&
$my_class->file_access_key_check(basename(__FILE__, '.php'), $_POST['check'])) {
// do stuff...
} else {
// friendly user message stating that the access to the file isn't autorized
}
Essentially, what is being done is to generate a key combining the file name and the session ID. Both must match otherwise the access isn't allowed.
Question:
Does this secures the access to the file or some considerations are to be made in order to actually secure the file that receives Ajax calls, thus preventing a direct browser access or the file being included within another one?