HTTP methods tell a PHP script what the client wants to do. A normal page visit usually sends a GET request. Submitting a form commonly sends POST. APIs add methods such as PUT, PATCH and DELETE.
The method name is simple. Handling its data correctly is where developers occasionally lose an afternoon wondering why $_POST is empty.
This guide explains how to detect HTTP request methods in PHP, access their input and reject methods an endpoint does not support.
Quick answer: How to detect the request method in PHP
PHP provides the current HTTP method through the REQUEST_METHOD element of the $_SERVER superglobal.
<?php
$requestMethod = $_SERVER['REQUEST_METHOD'] ?? 'UNKNOWN';
echo htmlspecialchars($requestMethod, ENT_QUOTES, 'UTF-8');
Its value is normally an uppercase method name such as GET, POST, PUT, PATCH or DELETE.
The following condition is the usual way to process a submitted POST form:
<?php
if (($_SERVER['REQUEST_METHOD'] ?? '') === 'POST') {
// Validate and process the submitted form.
}
Common HTTP request methods
An HTTP method describes the intended operation. PHP does not decide what each method means in your application, but your routes should follow the standard method semantics.
| Method | Typical purpose | Common input location |
|---|---|---|
| GET | Retrieve or filter data | URL query string |
| POST | Create data or submit a form | Request body |
| PUT | Replace a resource | Request body |
| PATCH | Partially update a resource | Request body |
| DELETE | Delete a resource | URL, route parameter or request body |
| HEAD | Retrieve response headers without a response body | Usually none |
| OPTIONS | Discover the methods and communication options supported by an endpoint | Usually none |
The HTTP request method reference defines the standard purpose and behaviour of these methods.
Handle multiple request methods with match
A PHP endpoint can inspect the method and route the request to the matching handler. A match expression keeps this logic compact when each method returns a value.
<?php
declare(strict_types=1);
$requestMethod = $_SERVER['REQUEST_METHOD'] ?? '';
$response = match ($requestMethod) {
'GET' => 'Retrieve a resource',
'POST' => 'Create a resource',
'PUT' => 'Replace a resource',
'PATCH' => 'Update part of a resource',
'DELETE' => 'Delete a resource',
default => 'Unsupported request method',
};
echo htmlspecialchars($response, ENT_QUOTES, 'UTF-8');
For an actual application, each branch would normally call a function, controller method or service instead of returning a description.
When these methods are used to build APIs, they are commonly organised as REST endpoints. See this PHP RESTful web service example for a practical implementation.
Use strict comparisons when checking method names. HTTP method names are case-sensitive, and PHP normally supplies REQUEST_METHOD in uppercase.
Read data from a GET request
GET data is sent in the URL query string. PHP parses it into the $_GET superglobal.
For this URL:
https://example.com/products.php?category=books&page=2
PHP makes the values available by their parameter names:
<?php
$category = $_GET['category'] ?? '';
$page = filter_input(INPUT_GET, 'page', FILTER_VALIDATE_INT);
if ($page === false || $page === null || $page < 1) {
$page = 1;
}
echo htmlspecialchars($category, ENT_QUOTES, 'UTF-8');
echo $page;
The null coalescing operator prevents an undefined array key warning when a parameter is missing. Validation is still required because query-string values are external input.
GET requests are suitable for searches, filters, pagination and other read-only operations. Their parameters remain visible in the URL and may be stored in browser history, logs and analytics systems. Do not put passwords, access tokens or other secrets in a query string.
Read data from a POST form
PHP populates $_POST when a request uses POST with an application/x-www-form-urlencoded or multipart/form-data body. These are the formats normally sent by HTML forms.
<form method="post" action="">
<label for="name">Name</label>
<input type="text" id="name" name="name" required>
<label for="email">Email</label>
<input type="email" id="email" name="email" required>
<button type="submit">Send</button>
</form>
The server can process the form only when the current request uses POST:
<?php
declare(strict_types=1);
$name = '';
$email = '';
$message = '';
if (($_SERVER['REQUEST_METHOD'] ?? '') === 'POST') {
$name = trim($_POST['name'] ?? '');
$email = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
if ($name === '') {
$message = 'Enter your name.';
} elseif ($email === false || $email === null) {
$message = 'Enter a valid email address.';
} else {
$message = 'The form was submitted successfully.';
}
}
Checking the request method prevents the processing code from running during the initial GET request. It also makes the expected behaviour of the endpoint clear.
Validation and output escaping solve different problems. Validate input according to the data your application accepts. Escape a value when placing it into HTML:
<p>
<?= htmlspecialchars($message, ENT_QUOTES, 'UTF-8') ?>
</p>
Why $_POST can be empty
An empty $_POST array does not always mean the request has no body. PHP fills $_POST only for supported form content types.
For example, a JavaScript client may send JSON:
{
"name": "John",
"email": "john@example.com"
}
Even when that request uses POST, its JSON values do not appear in $_POST. The script must read and decode the raw request body instead.
Read JSON from POST, PUT, PATCH or DELETE
Use php://input to read a raw request body. This works with JSON sent through POST, PUT, PATCH and DELETE requests.
The PHP manual documents php://input as a way to read raw request data from the request body.
<?php
declare(strict_types=1);
header('Content-Type: application/json; charset=utf-8');
$rawBody = file_get_contents('php://input');
if ($rawBody === false) {
http_response_code(400);
echo json_encode([
'error' => 'Unable to read the request body.',
]);
return;
}
try {
$data = json_decode($rawBody, true, 512, JSON_THROW_ON_ERROR);
} catch (JsonException $exception) {
http_response_code(400);
echo json_encode([
'error' => 'The request body contains invalid JSON.',
]);
return;
}
if (!is_array($data)) {
http_response_code(400);
echo json_encode([
'error' => 'The JSON body must contain an object.',
]);
return;
}
echo json_encode([
'received' => $data,
], JSON_PRETTY_PRINT);
JSON_THROW_ON_ERROR is safer than silently accepting a failed decode. It distinguishes malformed JSON from a valid JSON value such as null.
The raw request body is a stream. Read it once, decode it and pass the resulting array to the rest of the application. Repeatedly reading and decoding it in different functions makes request handling harder to follow.
Handle PUT and PATCH requests
PUT and PATCH are commonly used by APIs to update existing resources. They are related, but their intended meaning is different.
PUTreplaces the complete resource representation.PATCHupdates only the supplied fields.
Suppose an API stores this user:
{
"name": "Maya",
"email": "maya@example.com",
"status": "active"
}
A PUT request would normally send all fields required to replace that user. A PATCH request might send only the changed status:
{
"status": "inactive"
}
PHP does not automatically populate $_POST for PUT or PATCH requests. Read the JSON body from php://input and then process it according to the method.
<?php
declare(strict_types=1);
header('Content-Type: application/json; charset=utf-8');
$requestMethod = $_SERVER['REQUEST_METHOD'] ?? '';
if (!in_array($requestMethod, ['PUT', 'PATCH'], true)) {
http_response_code(405);
header('Allow: PUT, PATCH');
echo json_encode([
'error' => 'Method not allowed.',
]);
return;
}
$rawBody = file_get_contents('php://input');
try {
$data = json_decode(
$rawBody ?: '',
true,
512,
JSON_THROW_ON_ERROR
);
} catch (JsonException $exception) {
http_response_code(400);
echo json_encode([
'error' => 'Invalid JSON request body.',
]);
return;
}
if (!is_array($data)) {
http_response_code(400);
echo json_encode([
'error' => 'Expected a JSON object.',
]);
return;
}
if ($requestMethod === 'PUT') {
$requiredFields = ['name', 'email', 'status'];
$missingFields = array_diff($requiredFields, array_keys($data));
if ($missingFields !== []) {
http_response_code(422);
echo json_encode([
'error' => 'PUT requires all resource fields.',
'missing' => array_values($missingFields),
]);
return;
}
}
echo json_encode([
'method' => $requestMethod,
'data' => $data,
]);
The exact validation rules depend on the API. The important part is to keep the behaviour predictable. A PUT endpoint should not quietly behave like PATCH unless that behaviour is clearly documented.
Handle a DELETE request
A DELETE request identifies a resource and asks the server to remove it. The identifier is usually passed in the URL rather than the request body.
For example:
DELETE /api/users.php?id=42
The PHP endpoint can validate the method and identifier before performing the delete operation:
<?php
declare(strict_types=1);
header('Content-Type: application/json; charset=utf-8');
if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'DELETE') {
http_response_code(405);
header('Allow: DELETE');
echo json_encode([
'error' => 'Method not allowed.',
]);
return;
}
$userId = filter_input(INPUT_GET, 'id', FILTER_VALIDATE_INT);
if ($userId === false || $userId === null || $userId < 1) {
http_response_code(400);
echo json_encode([
'error' => 'A valid user ID is required.',
]);
return;
}
// Delete the authorised resource here.
http_response_code(204);
A successful DELETE request may return 204 No Content. In that case, do not send a response body.
Never treat possession of an ID as permission to delete the corresponding record. Authenticate the caller and confirm that the caller is authorised to delete that specific resource before running the database query.
Return 405 Method Not Allowed correctly
When a valid endpoint receives an unsupported method, return the 405 Method Not Allowed status. Include an Allow header listing the methods accepted by that endpoint.
<?php
declare(strict_types=1);
$allowedMethods = ['GET', 'POST'];
$requestMethod = $_SERVER['REQUEST_METHOD'] ?? '';
if (!in_array($requestMethod, $allowedMethods, true)) {
http_response_code(405);
header('Allow: ' . implode(', ', $allowedMethods));
header('Content-Type: application/json; charset=utf-8');
echo json_encode([
'error' => 'Method not allowed.',
]);
return;
}
Use 404 Not Found when the route or resource does not exist. Use 405 when the route exists but does not accept the requested method. That distinction helps API clients diagnose problems correctly.
Send HTTP requests to PHP with cURL
The following commands are useful for testing a PHP endpoint without building a separate frontend.
Send a GET request
curl "http://localhost/api.php?category=books&page=2"
Send a form-encoded POST request
curl -X POST \
-d "name=Maya" \
-d "email=maya@example.com" \
http://localhost/api.php
Send JSON with POST
curl -X POST \
-H "Content-Type: application/json" \
-d '{"name":"Maya","email":"maya@example.com"}' \
http://localhost/api.php
Send a PATCH request
curl -X PATCH \
-H "Content-Type: application/json" \
-d '{"status":"inactive"}' \
http://localhost/api.php
Send a DELETE request
curl -X DELETE \
"http://localhost/api.php?id=42"
During testing, check the response status as well as the response body. A JSON error message is less useful when the server accidentally returns 200 OK for every failure.
Security considerations when handling request methods
Checking the request method is only the first step. The data sent with a request should always be treated as untrusted input.
A common mistake is assuming that a POST request is safe because it comes from your own form. A user can send a request manually using browser tools, cURL or API clients such as Postman.
Keep these practices in mind:
- Validate every value received from
$_GET,$_POSTorphp://input. - Escape output before displaying user-controlled values in HTML.
- Use prepared statements when storing request data in a database.
- Protect state-changing requests with CSRF tokens when they are triggered from browser forms.
- Authenticate users before allowing protected actions such as updates and deletes.
- Limit accepted request methods instead of allowing unexpected methods to reach application code.
Request method checking helps organise your application, but it does not provide authentication or authorisation. A DELETE request from an unauthorised user is still a DELETE request.
Common errors when working with PHP request methods
Checking $_POST for JSON requests
Problem: An API client sends JSON, but $_POST is empty.
Cause: PHP only fills $_POST for form-encoded request bodies. JSON must be read separately.
Fix:
<?php
$body = file_get_contents('php://input');
$data = json_decode($body, true);
Using GET for sensitive information
Problem: Passwords or private tokens appear in URLs.
Cause: GET parameters are visible in browser history, server logs and shared links.
Fix: Use POST or another appropriate method and protect the data with proper authentication and encryption.
Accepting every request method
Problem: An endpoint behaves unexpectedly when called with an unsupported method.
Cause: The script processes requests without checking what operation was requested.
Fix: Validate the method early and return 405 Method Not Allowed for unsupported requests.
Forgetting that HTTP methods do not enforce permissions
Problem: A user can call an update or delete endpoint directly.
Cause: The application checks only whether the request is PATCH or DELETE, but not whether the user has permission.
Fix: Add authentication and authorisation checks before performing protected operations.
PHP request methods FAQ
What is the default request method in PHP?
The default method used when opening a URL in a browser is GET. PHP reads this value through $_SERVER['REQUEST_METHOD'].
How do I check if a request is POST in PHP?
Compare $_SERVER['REQUEST_METHOD'] with POST.
<?php
if (($_SERVER['REQUEST_METHOD'] ?? '') === 'POST') {
echo 'POST request';
}
How do I get PUT data in PHP?
PHP does not create a $_PUT superglobal. Read the raw request body from php://input and decode the data according to its content type. For a complete example of receiving JSON payloads in PHP, see receiving JSON POST data in PHP.
<?php
$input = file_get_contents('php://input');
$data = json_decode($input, true);
Can PHP handle PATCH and DELETE requests?
Yes. PHP can receive any standard HTTP method. You detect the method using $_SERVER['REQUEST_METHOD'] and read the request body when required.
What is the difference between POST and PUT in PHP?
POST is commonly used to create a new resource or submit data. PUT is generally used to replace an existing resource. The difference is based on HTTP semantics, not on a special PHP feature.
How do I test different HTTP methods?
You can use tools such as cURL, Postman or browser developer tools. If you want to send HTTP requests directly from PHP code, see this PHP cURL guide. cURL is often the quickest option while developing a PHP API because it lets you control the method, headers and request body directly.
Conclusion
PHP makes request handling straightforward. The $_SERVER['REQUEST_METHOD'] value tells you what operation the client requested, while $_GET, $_POST and php://input provide access to the submitted data.
If you want to learn more about accessing submitted form values from PHP forms, see this guide on accessing form data in PHP.
For simple forms, checking GET and POST is usually enough. For APIs, understanding PUT, PATCH and DELETE becomes important because the method communicates the intended action.
The key habit is to treat every request as external input. Check the method, validate the data and only perform actions the current user is allowed to perform.
Thank you, better than any book.
Welcome Gaurav.
Only now I have understood the difference between methods.
Thank you Jai.
Thank you for the excellent tutorial.
Welcome Shrikant