This question already has an answer here:
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
</div>
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);
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).