Mike Moore
Mike Moore

Reputation: 7478

Is this a reliable way to check the REQUEST_METHOD?

In my class, AController, I have the following method:

private function determineRequestMethod()
{
  if($_SERVER['REQUEST_METHOD'] == 'POST')
  {
    $this->requestMethod = AController::POST;
  }
  else
  {
    $this->requestMethod = AController::GET;
  }
}

This method is called from the constructor. POST and GET are class constants, and requestMethod is a class variable.

PS - $_SERVER['REQUEST_METHOD'] does work on my server.

I have updated the method to specifically check for GET and to throw an exception when the request method is not GET or POST:

private function determineRequestMethod()
{
    if($_SERVER['REQUEST_METHOD'] == AController::POST) 
    {
        $this->requestMethod = AController::POST;
    } 
    else if($_SERVER['REQUEST_METHOD'] == AController::GET)
    {
        $this->requestMethod = AController::GET;
    }
    else
    {
        throw new Exception('Unexpected request method [' . $_SERVER['REQUEST_METHOD'] . '].');
    }
}

Upvotes: 1

Views: 558

Answers (3)

Sarfraz
Sarfraz

Reputation: 382826

Yes it is realiable, you could actually do:

private function determineRequestMethod()
{
  if($_SERVER['REQUEST_METHOD'] == 'POST')
  {
    $this->requestMethod = AController::POST;
  }
  elseif($_SERVER['REQUEST_METHOD'] == 'GET')
  {
    $this->requestMethod = AController::GET;
  }
}

If your class also supports other methods, you might want to put it in else condition otherwise your code is fine.

PS - $_SERVER['REQUEST_METHOD'] does work on my server.

It should work elsewhere too :)

Upvotes: 2

Otar
Otar

Reputation: 2591

Why complicating life when there's an excellent native input filter in PHP: filter_input().

Upvotes: -1

Bojan Rajkovic
Bojan Rajkovic

Reputation: 1706

I don't know of any other way to check the request method in PHP, so I would say it is. You may want to watch out for things like HEAD and other HTTP verbs though--treating them all as GET's may not be what you want.

Upvotes: 1

Related Questions