PHP Functions for Detecting HTTP Request Types (GET, POST, PUT, DELETE, PATCH, AJAX)
This article provides PHP code snippets to determine the HTTP request method—such as GET, POST, PUT, DELETE, PATCH—and to check for AJAX requests, offering a quick reference for developers implementing RESTful APIs in a backend environment.
RESTful APIs are widely used in modern backend development, and detecting the HTTP request method is essential for handling client interactions correctly.
1. Get Request Method
function get_request_method() {
return $_SERVER['REQUEST_METHOD'];
}2. Is POST Request
function is_post() {
if ($_POST) {
return true;
} else {
return false;
}
}3. Is GET Request
function is_get() {
if ($_GET) {
return true;
} else {
return false;
}
}4. Is PUT Request
function is_put() {
if ($_SERVER['REQUEST_METHOD'] == 'PUT') {
return true;
} else {
return false;
}
}5. Is PATCH Request
function is_patch() {
if ($_SERVER['REQUEST_METHOD'] == 'PATCH') {
return true;
} else {
return false;
}
}6. Is DELETE Request
function is_delete() {
if ($_SERVER['REQUEST_METHOD'] == 'DELETE') {
return true;
} else {
return false;
}
}7. Is AJAX Request
function is_ajax() {
if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
return true;
} else {
return false;
}
}These utility functions can be copied directly into a PHP project to quickly enable request-type detection for RESTful services.
Laravel Tech Community
Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.