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

Viewed 28

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

0 Answers
Related