tags:

views:

50

answers:

3

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'] . '].');
    }
}
+1  A: 

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.

B.R.
Thanks that is an excellent point. I have adjusted my method to reflect your advice.
letseatfood
A: 

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

Otar
-1 Because OP never said anything about input variables or filtering, which is a completely different domain from checking various HTTP request methods.
BoltClock
Dammit, is that hard to switch REQUEST_METHOD and return input filter based on the switch case? switch ($_SERVER['REQUEST_METHOD']){case 'GET': return filter_input_array(INPUT_GET);case 'POST': return filter_input_array(INPUT_POST);default: return array();}
Otar
+2  A: 

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 :)

Sarfraz