To detect the request type (i.e., whether the request is a GET, POST, PUT, DELETE, etc.) in PHP, you can use the $_SERVER['REQUEST_METHOD']
variable. This variable contains the request method as a string, such as 'GET'
, 'POST'
, 'PUT'
, 'DELETE'
, etc.
Here is an example of how to use the $_SERVER['REQUEST_METHOD']
variable 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
}
In this example, the $_SERVER['REQUEST_METHOD']
variable is checked against the different request methods using the if
statement. If the request method is 'GET'
, the code in the first block will be executed; if the request method is 'POST'
, the code in the second block will be executed, and so on.
You can also use the switch
statement to detect the request type, like this:
<?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;
}
Note that the $_SERVER['REQUEST_METHOD']
variable is case-sensitive, so you should use the exact request method strings (e.g., 'GET'
, 'POST'
, etc.) when checking it.