129

How can I find out which method (usually GET or POST) is used for the current request?

Dominic Rodger
  • 97,747
  • 36
  • 197
  • 212
eflorico
  • 3,589
  • 2
  • 30
  • 41

2 Answers2

228
$_SERVER['REQUEST_METHOD']

See the docs. It will contain the request method upper-cased (i.e. 'GET', 'HEAD', 'POST', 'PUT').

Dominic Rodger
  • 97,747
  • 36
  • 197
  • 212
18

While checking

$_SERVER['REQUEST_METHOD']

seems the obvious choice, since some of the people are advocating safe superglobals alternatives (Is using superglobals directly good or bad in PHP? and similar questions), one may instead use automatic sanitizing

filter_input( \INPUT_SERVER, 'REQUEST_METHOD', \FILTER_SANITIZE_SPECIAL_CHARS )

(you might of course use other filter, eg. FILTER_SANITIZE_STRING - see here for a full list).

Obviously, in the regular (GET/POST) case there ain't anything to sanitize, but a good habit is still a good habit IMO.

http://php.net/manual/en/reserved.variables.server.php

http://php.net/manual/en/function.filter-input.php

  • If you just want to know whether it is `GET` or `POST` or such, no filtering is required. However, you want to test the method and if not matched as expected, you can fallback to the "non-understood HTTP method" error (HTTP code 405). https://en.wikipedia.org/wiki/List_of_HTTP_status_codes#405 – Alexis Wilke Jul 16 '17 at 04:46
  • @AlexisWilke like I said, `in the regular (GET/POST) case there ain't anything to sanitize`; OTOH, if the result (the value of the variable) is, e.g. (and for whatever reason) further used as e.g. part of a output string or a autogenerated script body, and (again, for whatever reason) if the web server is bugged [(and there are bugs in web servers)](http://archive.apache.org/gnats/) and prone to injecting an invalid request method, this could *potentially* (albeit it's of course extremely unlikely) [result in arbitrary code execution or data generation](https://xkcd.com/327/). –  Jul 16 '17 at 20:17
  • 1
    @MichaelJaros that's why I've written "possibly with (...) `FILTER_SANITIZE_SPECIAL_CHARS`" - but you're right, it's currently not clear enough, I rephrased it. –  Jun 28 '19 at 10:39