W3docs

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

In PHP, you can use the $_SERVER['REQUEST_METHOD'] superglobal to detect the request type.

In PHP, you can use the $_SERVER['REQUEST_METHOD'] superglobal to detect the request type. This superglobal will contain the request method used by the client, which can be one of GET, POST, PUT, or DELETE.

Here's an example of how you can use this superglobal to detect the request type:

Example of detecting request type in PHP

<?php

if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    // handle GET request
} elseif ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // handle POST request
} elseif ($_SERVER['REQUEST_METHOD'] === 'PUT') {
    // handle PUT request
} elseif ($_SERVER['REQUEST_METHOD'] === 'DELETE') {
    // handle DELETE request
}

<div class="alert alert-info flex not-prose"> Watch a course <span class="hidden md:block">Watch a video course </span> Learn object oriented PHP</div>

You can also use a switch statement to handle the different request types:

Example of detecting request type in PHP using a switch statement

<?php

switch ($_SERVER['REQUEST_METHOD']) {
    case 'GET':
        // handle GET request
        break;
    case 'POST':
        // handle POST request
        break;
    case 'PUT':
        // handle PUT request
        break;
    case 'DELETE':
        // handle DELETE request
        break;
}