boo-urns
boo-urns

Reputation: 10376

Do you have to check whether 'REQUEST_METHOD' exists in the $_SERVER variable before using it?

Do I have to check whether the $_SERVER variable has a key REQUEST_METHOD before actually using $_SERVER['REQUEST_METHOD']?

That is, is it overly defensive to always check whether a key exists in array variable like $_SERVER?

Upvotes: 6

Views: 1244

Answers (3)

MrCode
MrCode

Reputation: 64536

If your script is interested in the value in REQUEST_METHOD then it's probably run from a web browser not the CLI, so in that case I wouldn't bother doing an isset() check. REQUEST_METHOD will always be there unless running from the CLI, since by definition of HTTP, a browser can't request a page without a request method.

Upvotes: 1

davidethell
davidethell

Reputation: 12018

Since you can't really ever guarantee what keys any PHP array will have you should always check them. That is not overly defensive and is good practice on your part.

For the sake of other readers with similar questions, you'd generally choose among these three methods for checking the array:

array_key_exists("REQUEST_METHOD", $_SERVER)

or

isset($_SERVER['REQUEST_METHOD'])

or else you should escape the warnings with @:

$someVar = @$_SERVER['REQUEST_METHOD'];

The last option is definitely not recommended as it tends to hide problems so I'd stick with the practice of checking for the presence of keys on any array, even the global PHP arrays.

Upvotes: 5

johankj
johankj

Reputation: 1767

The PHP-manual says the following about the $_SERVER-variable:

There is no guarantee that every web server will provide any of these; servers may omit some, or provide others not listed here. That said, a large number of these variables are accounted for in the » CGI/1.1 specification, so you should be able to expect those.

The CGI/1.1 specification has the following to say:

The REQUEST_METHOD meta-variable MUST be set to the method which
should be used by the script to process the request, as described in
section 4.3.

and

The Request Method, as supplied in the REQUEST_METHOD meta-variable, identifies the processing method to be applied by the script in
producing a response. The script author can choose to implement the
methods most appropriate for the particular application. If the
script receives a request with a method it does not support it SHOULD reject it with an error (see section 6.3.3).

It probably isn't necessary to check for its existense if you aren't doing any CLI-development and the script will only be run from a server like Apache. You could probably do it, to be on the safe side, but it is of no necessity.

Upvotes: 5

Related Questions