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. 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:
<?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
}
Watch a video course
Learn object oriented PHP
You can also use a switch statement to handle the different request types:
<?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;
}