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 determ开发者_Go百科ineRequestMethod()
{
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'] . '].');
}
}
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 :)
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.
Why complicating life when there's an excellent native input filter in PHP: filter_input().
精彩评论