Detecting request type in PHP (GET, POST, PUT or DELETE)

前端 未结 13 1661
不思量自难忘°
不思量自难忘° 2020-11-22 08:02

How can I detect which request type was used (GET, POST, PUT or DELETE) in PHP?

13条回答
  •  日久生厌
    2020-11-22 08:24

    Detecting the HTTP method or so called REQUEST METHOD can be done using the following code snippet.

    $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
    }
    

    You could also do it using a switch if you prefer this over the if-else statement.

    If a method other than GET or POST is required in an HTML form, this is often solved using a hidden field in the form.

    
    

    For more information regarding HTTP methods I would like to refer to the following StackOverflow question:

    HTTP protocol's PUT and DELETE and their usage in PHP

提交回复
热议问题