I have a PHP script (myscript.php) that is run from a JS script and would like to prevent it from being run by just typing myscript.php in the browser.
I thought checking php_sapi_name() might be an answer (and it still might be), but I can’t seem to check the values it’s returning in each case.
document.querySelector(".mylink")
.addEventListener("click", function () {
fetch("myscript.php")
})
// determine if the request was an ajax request
define('IS_AJAX_REQUEST', isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');
You can then test if(IS_AJAX_REQUEST) is true or not in your logic.
Pretty much going to be impossible to check, short of encoding a key to hand to the browser to pass back to the server (think JWT). Wont stop someone from going to the page, getting the key, and postmastering their way in, but… at that point, whats the difference between a user’s browser going to the url and javascript in the users browser going to the url, really.
I should say i’m not a fan of checking headers for anything as reliable.
No, it’s not a question of authentication. There’s no money or security running on this. myscript just increases a counter. Sounds like a custom header would do what I need even if it’s not infallible.
Have you considered an outbound link tracker? i.e. instead of linking directly to the external resource, you link to https://my.website.example/outbound?url=https://some.external.website.example/some/path where you register the click and then redirect (using HTTP 302) to https://some.external.website.example/some/path.
Drawback is that it’s a little bit slower, advantages are you problem disappears and it works without JS.