Dexty
Dexty

Reputation: 1472

Block direct access to PHP files and allow json

I'm trying to block out some files with a php script, however, i want my javascript ajax calls to allow the scripts, i don't know if this is even possible but..

What i do now is,

$filename = array('index.php');

$basename = basename($_SERVER['REQUEST_URI']);

if(!in_array($basename, $filename)) {
    die('...');
}

This will block all files and not index.php, but what if i have an login.php that makes my ajax calls possible?

Upvotes: 1

Views: 1538

Answers (1)

Daff
Daff

Reputation: 44205

When you send a JavaScript AJAX call it adds

X-Requested-With : XmlHTTPRequest

To the HTTP headers. So if you want to do something in case of an AJAX call you can check for something like this:

$headers = getallheaders();
if($headers['X-Requested-With') == 'XMLHttpRequest') {
    // ...
}

Keep in mind that any HTTP client can modify headers, so it doesn't really add any security (but e.g. a browser couldn't call your PHP scripts directly with the default settings).

Upvotes: 2

Related Questions