Jamesking56
Jamesking56

Reputation: 3901

Block direct access to PHP file except from AJAX request?

I wish to have a webpage that uses AJAX to access a PHP file in ./ajax/file.ajax.php

Trouble is, I don't want people to be able to type the address in their browser to access that PHP file directly.

Is there a way I can make it so that only AJAX requests can access the file?

Is there something I can check for in the PHP file to achieve this?

Upvotes: 3

Views: 2249

Answers (2)

Mahdi
Mahdi

Reputation: 9407

If you're not using jQuery or you are not interested/you can't use custom headers (to go with what alex has offered), you may just simple POST some data with your Ajax request, and in that specific file check if that data has sent or not. If you send by GET it would be visible on the address bar, that's why I suggest POST.

<?php

if (empty($_POST['valid_ajax']))
    header('Location: /');

?>

It's not solid as you can fool that with providing handmade data, however that's better than nothing if your problem is not that critical.

Upvotes: 1

alex
alex

Reputation: 490133

If you're using jQuery to make the XHR, it will set a custom header X-Requested-With. You can check for that and determine how to serve your response.

$isXhr = isset($_SERVER["HTTP_X_REQUESTED_WITH"])
         AND strotlower($_SERVER["HTTP_X_REQUESTED_WITH"]) == "xmlhttprequest";

However, this is trivial to spoof. In the past, I've used this to decide whether to render a whole page (if not set) or a page fragment (if set, to be injected into current page).

Upvotes: 4

Related Questions