0

I use this code to disallow direct access to php file

if (__FILE__ == $_SERVER['DOCUMENT_ROOT'].$_SERVER['PHP_SELF']){
  die("Direct access forbidden");
}

My problem is I need to call the php this way

xmlhttp.open("GET","getverse.php",true);

it also return Direct access forbidden error.

How can I allow this call to php file while disallowing direct access to it from a browser?

Thanks

Wayne
  • 763
  • 4
  • 21
  • 43
  • 1
    You can establish some sort of authentication protocol, but ultimately an HTTP request is an HTTP request. If your site responds to ajax (HTTP) requests, it can be fooled into responding to a request from any HTTP client on the internet. – Pointy Oct 10 '18 at 13:12
  • Consider what you're trying to do... You want to allow access while simultaneously disallowing access. Time to reconsider the problem you're trying to solve. Does the user have access to this service or not? What are you actually trying to prevent the user from doing and why? – David Oct 10 '18 at 13:13
  • @David, I think I already mentioned the different scenario. `xmlhttp.open("GET","getverse.php",true);` is being called from a javascript file which I want to allow. Direct access to a php file from a browser address bar is the one that should not be allowed. I was hoping there is some ways to make these 2 different from a technical stand point and disallow the direct browser access – Wayne Oct 10 '18 at 15:42
  • @Wayne: But *why*? What are you trying to prevent? Consider the underlying goal, not the current attempted implementation. What is that goal? There’s a pretty good chance that the attempt isn’t the right way to achieve that goal. But you’re not asking about the goal, you’re asking about the attempt. – David Oct 10 '18 at 15:46
  • @David, I think I get your point. Thanks. That is a freaking good point. – Wayne Oct 10 '18 at 15:49
  • @David, just to close this, the goal is simply not to allow direct access to php file from a browser address bar. an answer below meet that goal and accepted as answer. – Wayne Oct 10 '18 at 21:14

2 Answers2

0

Am not sure its just a single PHP file or you are using any Framework or a CMS.

But you can try,

if (__FILE__ == $_SERVER['DOCUMENT_ROOT'].$_SERVER['PHP_SELF'] && !isset($_GET['ajax'])){
  die("Direct access forbidden");
}  

Invoke this file using

xmlhttp.open("GET","getverse.php?ajax=1",true);
Mangesh Sathe
  • 1,987
  • 4
  • 21
  • 40
0

You can do something like that:

if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {...}

but remember you can spoof any header with cURL anyway:

curl_setopt($ch,CURLOPT_HTTPHEADER,array("X-Requested-With : XMLHttpRequest"));

(but at least it should take care of accessing the PHP file directly in the browser).