$_SERVER['REQUEST_METHOD'] does not exist

user1637261 picture user1637261 · Oct 5, 2012 · Viewed 10.5k times · Source

I've just installed WAMP and I can access localhost and get the phpinfo() output.

However, although I can see _SERVER['REQUEST_METHOD'] is set to GET, I'm trying to use the following PHP:

if ($_SERVER["REQUEST_METHOD"]=="POST") {
  ...

but it produces this error:

PHP Notice: Undefined index: REQUEST_METHOD in C:\ ... \test.php on line 40

Using Komodo to stop at line 40 and check $_SERVER - it does not have 'REQUEST_METHOD' in the array at all - not even GET.

Anyone have any ideas? Do I have to enable POST, REQUEST_METHOD?

Why can I see REQUEST_METHOD=GET in the phpinfo but not in the PHP script.

I also tried this:

<?php
ob_start();
phpinfo();
$info = ob_get_contents();
ob_end_clean();
?>

I generates some of the phpinfo (as viewed in the browser using localhost/?phpinfo=1) but not all of it. Why not?

Answer

Xeoncross picture Xeoncross · Oct 5, 2012

Most $_SERVER directives are set by the web server. If you are using WAMP that would be Apache. You can check your apache config to find out why this value isn't set.

It's better to test for the existence of values before trying to use them.

$value = isset($_SERVER['REQUEST_METHOD']) ? $_SERVER['REQUEST_METHOD'] : null;

You can even use the getenv() method to shorten this.

$value = getenv('REQUEST_METHOD');

Also there is no need to do

<?php
ob_start();
phpinfo();
$info = ob_get_contents();
ob_end_clean();
?>

This is all you need in a blank PHP file.

<?php phpinfo();

I would write your example like this:

$request_method = strtoupper(getenv('REQUEST_METHOD'));
$http_methods = array('GET', 'POST', 'PUT', 'DELETE', 'HEAD', 'OPTIONS');

if( ! in_array($request_method, $http_methods)
{
    die('invalid request');
}