130

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

0

2 Answers 2

236
$_SERVER['REQUEST_METHOD'] 

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

Sign up to request clarification or add additional context in comments.

Comments

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

3 Comments

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). en.wikipedia.org/wiki/List_of_HTTP_status_codes#405
@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) 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.
@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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.