How to only allow POST requests in PHP so people can’t access the file directly

Issue

This Content is from Stack Overflow. Question asked by simplon78

I’m making an API call from a file called markets.php to receive from financial data.

My website frontend (on a different URL) makes a POST request to mydomain.com/markets.php, which works fine – no problems there. However, I’d like to block direct access to markets.php so if anyone were to visit it in the browser, they couldn’t access it.

Right now, I’ve limited requests to only come from my frontend as per below

Access-Control-Allow-Origin: myfrondenddomain.com

That works fine, and no other URLs seem to be able to make requests. However if I visit the API file directly, mydomain.com/markets.php, it allows access and makes the call.

I tried adding the header to force only POST requests. Doesn’t seem to do anything

header("Access-Control-Request-Method: POST");

I also tried to limit request methods to post only as per below but then I Get a 500 error when I make a post request

if($_SERVER['REQUEST_METHOD'] != "POST") {
 header("HTTP/1.0 403 Forbidden");
 print("Forbidden");
 exit();
}

Any ideas? I want to be able to lock requests to purely come from my domain, and not be able to visit the file in browser



Solution

This question is not yet answered, be the first one who answer using the comment. Later the confirmed answer will be published as the solution.

This Question and Answer are collected from stackoverflow and tested by JTuto community, is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?