Wykrywanie typu żądania w PHP (GET, POST, PUT lub DELETE)

Jak mogę wykryć, który typ żądania został użyty (GET, POST, PUT lub DELETE) w PHP?

 796
Author: Peter Mortensen, 2008-12-11

11 answers

Używając

$_SERVER['REQUEST_METHOD']

Przykład

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
     // The request is using the POST method
}

Więcej szczegółów można znaleźć w dokumentacji zmiennej $_SERVER .

 1126
Author: gnud,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-08-22 13:39:38

Odpoczynek w PHP można zrobić całkiem prosto. Create http://example.com/test.php (przedstawione poniżej). Użyj tego do wywołań REST, np. http://example.com/test.php/testing/123/hello . działa to z Apache i Lighttpd po wyjęciu z pudełka i nie są potrzebne żadne reguły przepisywania.

<?php
$method = $_SERVER['REQUEST_METHOD'];
$request = explode("/", substr(@$_SERVER['PATH_INFO'], 1));

switch ($method) {
  case 'PUT':
    do_something_with_put($request);  
    break;
  case 'POST':
    do_something_with_post($request);  
    break;
  case 'GET':
    do_something_with_get($request);  
    break;
  default:
    handle_error($request);  
    break;
}
 206
Author: neu242,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-02-18 15:46:18

Wykrywanie metody HTTP lub tzw. REQUEST METHOD można wykonać za pomocą poniższego fragmentu kodu.

$method = $_SERVER['REQUEST_METHOD']
if ($method == 'POST') {
    // Method is POST
} elseif ($method == 'GET') {
    // Method is GET
} elseif ($method == 'PUT') {
    // Method is PUT
} elseif ($method == 'DELETE') {
    // Method is DELETE
} else {
    // Method unknown
}

Możesz to również zrobić używając switch, jeśli wolisz to niż if-else.

Jeśli w formularzu html wymagana jest metoda inna niż GET lub POST, często rozwiązuje się to za pomocą ukrytego pola w formularzu.

<!-- DELETE method -->
<form action='' method='POST'>
    <input type="hidden" name'_METHOD' value="DELETE">
</form>

<!-- PUT method -->
<form action='' method='POST'>
    <input type="hidden" name'_METHOD' value="PUT">
</form>

Aby uzyskać więcej informacji na temat metod HTTP, chciałbym odnieść się do następującego pytania StackOverflow:

Protokół HTTP jest PUT i DELETE i ich użycie w PHP

 16
Author: Peter,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 12:26:32

Ponieważ chodzi o REST, samo pobranie metody request z serwera nie wystarczy. Musisz również otrzymać pełne parametry trasy. Powodem oddzielenia parametrów RESTful od parametrów GET / POST / PUT jest to, że zasób musi mieć własny unikalny adres URL do identyfikacji.

Oto jeden ze sposobów implementacji tras RESTful w PHP przy użyciu Slim:

Https://github.com/codeguy/Slim

$app = new \Slim\Slim();
$app->get('/hello/:name', function ($name) {
  echo "Hello, $name";
});
$app->run();

I odpowiednio skonfigurować serwer.

Oto inny przykład użycia AltoRouter:

Https://github.com/dannyvankooten/AltoRouter

$router = new AltoRouter();
$router->setBasePath('/AltoRouter'); // (optional) the subdir AltoRouter lives in

// mapping routes
$router->map('GET|POST','/', 'home#index', 'home');
$router->map('GET','/users', array('c' => 'UserController', 'a' => 'ListAction'));
$router->map('GET','/users/[i:id]', 'users#show', 'users_show');
$router->map('POST','/users/[i:id]/[delete|update:action]', 'usersController#doAction', 'users_do');
 7
Author: nurettin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-12-16 12:32:47

Możesz użyć funkcji getenv i nie musisz pracować ze zmienną $_SERVER:

getenv('REQUEST_METHOD');

Więcej informacji:

Http://php.net/manual/en/function.getenv.php

 6
Author: Artegon,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-03-04 12:35:33

Możemy również użyć input_filter do wykrycia metody żądania, jednocześnie zapewniając bezpieczeństwo poprzez input sanitation.

$request = filter_input(INPUT_SERVER, 'REQUEST_METHOD', FILTER_SANITIZE_ENCODED);
 5
Author: HelpNeeder,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-09-29 16:10:44

Jest to bardzo proste, wystarczy użyć $_SERVER ['REQUEST_METHOD'];

Przykład:

<?php
$method = $_SERVER['REQUEST_METHOD'];
switch ($method) {
  case 'GET':
    //Here Handle GET Request 
    break;
  case 'POST':
    //Here Handle POST Request 
    break;
  case 'DELETE':
    //Here Handle DELETE Request 
    break;
  case 'PUT':
    //Here Handle PUT Request 
    break;
}
?>
 4
Author: Juned Ansari,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-04-13 12:52:35
$request = new \Zend\Http\PhpEnvironment\Request();
$httpMethod = $request->getMethod();

W ten sposób można również osiągnąć w zend framework 2. Dzięki.

 3
Author: Amit Patange,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-07-06 11:11:18

W core php możesz zrobić tak:

<?php

$method = $_SERVER['REQUEST_METHOD'];

switch ($method) {
  case 'GET':
    //Here Handle GET Request
    echo 'You are using '.$method.' Method';
    break;
  case 'POST':
    //Here Handle POST Request
    echo 'You are using '.$method.' Method';
    break;
  case 'PUT':
    //Here Handle PUT Request
    echo 'You are using '.$method.' Method';
    break;
  case 'PATCH':
    //Here Handle PATCH Request
    echo 'You are using '.$method.' Method';
    break;
  case 'DELETE':
    //Here Handle DELETE Request
    echo 'You are using '.$method.' Method';
    break;
  case 'COPY':
      //Here Handle COPY Request
      echo 'You are using '.$method.' Method';
      break;

  case 'OPTIONS':
      //Here Handle OPTIONS Request
      echo 'You are using '.$method.' Method';
      break;
  case 'LINK':
      //Here Handle LINK Request
      echo 'You are using '.$method.' Method';
      break;
  case 'UNLINK':
      //Here Handle UNLINK Request
      echo 'You are using '.$method.' Method';
      break;
  case 'PURGE':
      //Here Handle PURGE Request
      echo 'You are using '.$method.' Method';
      break;
  case 'LOCK':
      //Here Handle LOCK Request
      echo 'You are using '.$method.' Method';
      break;
  case 'UNLOCK':
      //Here Handle UNLOCK Request
      echo 'You are using '.$method.' Method';
      break;
  case 'PROPFIND':
      //Here Handle PROPFIND Request
      echo 'You are using '.$method.' Method';
      break;
  case 'VIEW':
      //Here Handle VIEW Request
      echo 'You are using '.$method.' Method';
      break;
  Default:
    echo 'You are using '.$method.' Method';
  break;
}


?>
 0
Author: Shaan Ansari,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-08-03 14:00:02

Gdy zażądano metody, będzie ona miała array. Więc po prostu sprawdź za pomocą count().

$m=['GET'=>$_GET,'POST'=>$_POST];
foreach($m as$k=>$v){
    echo count($v)?
    $k.' was requested.':null;
}

3v4l.org/U51TE

 -1
Author: Thielicious,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-09-17 12:52:45

Możesz uzyskać dowolne dane ciągu zapytania TJ www.example.com?id=2&name=r

Musisz uzyskać dane za pomocą $_GET['id'] lub $_REQUEST['id'].

Post data oznacza formularz <form action='' method='POST'> musisz użyć $_POST lub $_REQUEST.

 -4
Author: Rockers Technology,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-04-23 10:23:23