Question

How to Detect HTTP Request Methods in PHP (GET, POST, PUT, DELETE)

phphttprequest

Question

In PHP, how can I determine which HTTP request method was used for the current request, such as GET, POST, PUT, or DELETE?

Short Answer

By the end of this page, you will understand how PHP exposes the current HTTP request method, how to check for methods like GET, POST, PUT, and DELETE, and how this is commonly used in form handling, APIs, routing, and request validation.

Concept

PHP provides information about the current HTTP request through the $_SERVER superglobal. To detect the request type, you usually read $_SERVER['REQUEST_METHOD'].

$method = $_SERVER['REQUEST_METHOD'];

This value contains the HTTP method used by the client, such as:

  • GET
  • POST
  • PUT
  • DELETE
  • PATCH
  • OPTIONS

This matters because web applications often behave differently depending on the request method:

  • GET usually retrieves data
  • POST usually creates or submits data
  • PUT usually updates or replaces data
  • DELETE usually removes data

In real programming, checking the request method is a basic part of:

  • building APIs
  • processing forms
  • writing simple routers
  • validating allowed actions
  • returning proper error responses

The key idea is that the URL alone is not always enough to decide what the server should do. The HTTP method provides extra meaning about the action being requested.

Mental Model

Think of an HTTP request like a labeled delivery envelope.

  • The URL tells you where the envelope should go.
  • The request method tells you what kind of action the sender wants.

For example:

  • GET = “Please show me the information.”
  • POST = “Please send this new information.”
  • PUT = “Please replace or update this information.”
  • DELETE = “Please remove this information.”

In PHP, $_SERVER['REQUEST_METHOD'] is the label on that envelope. Your code reads the label and decides how to handle the request.

Take Quiz

Syntax and Examples

The basic syntax is:

$method = $_SERVER['REQUEST_METHOD'];

You can compare it with specific method names:

if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    echo 'This is a GET request';
}

Example: Checking multiple request methods

<?php
$method = $_SERVER['REQUEST_METHOD'];

if ($method === 'GET') {
    echo 'Fetch data';
} elseif ($method === 'POST') {
    echo 'Create data';
} elseif ($method === 'PUT') {
    echo 'Update data';
} elseif ($method === 'DELETE') {
    echo 'Delete data';
} else {
    echo 'Unsupported request method';
}

This example reads the method once, stores it in $method, and then uses conditional logic to decide what action to take.

Example: Using switch

<?php
switch ($_SERVER['REQUEST_METHOD']) {
    case 'GET':
        echo 'Handle GET';
        break;
    case 'POST':
        echo 'Handle POST';
        break;
    case 'PUT':
        echo 'Handle PUT';
        break;
    case 'DELETE':
        echo 'Handle DELETE';
        break;
    default:
        http_response_code(405);
        echo 'Method Not Allowed';
}

This style is often cleaner when you have several possible methods.

Example: Detecting and reading a PUT body

<?php
if ($_SERVER['REQUEST_METHOD'] === 'PUT') {
    $rawBody = file_get_contents('php://input');
    echo $rawBody;
}

For PUT and DELETE, data is often sent in the raw request body rather than automatically appearing in $_POST.

Step by Step Execution

Consider this example:

<?php
$method = $_SERVER['REQUEST_METHOD'];

if ($method === 'POST') {
    echo 'Form submitted';
} else {
    echo 'Show form';
}

Step by step:

  1. PHP receives an HTTP request.
  2. The web server passes request details to PHP.
  3. PHP stores the request method in $_SERVER['REQUEST_METHOD'].
  4. The code copies that value into $method.
  5. The if statement checks whether $method is exactly 'POST'.
  6. If it is POST, PHP prints Form submitted.
  7. If it is not POST (for example GET), PHP prints Show form.

Example trace

If the browser visits the page normally:

REQUEST_METHOD = GET

Result:

Show form

If a form submits data to the same page with method POST:

REQUEST_METHOD = POST

Result:

Form submitted

Real World Use Cases

Checking the request method is common in many PHP applications.

1. Form handling

A page may show a form on GET and process it on POST.

if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    echo 'Display form';
} elseif ($_SERVER['REQUEST_METHOD'] === 'POST') {
    echo 'Process submitted data';
}

2. REST-style APIs

An API endpoint may use the same URL with different methods:

  • GET /users/5 → fetch a user
  • PUT /users/5 → update a user
  • DELETE /users/5 → delete a user

3. Route protection

You may allow only certain methods for an endpoint.

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    exit('Only POST is allowed');
}

4. AJAX or frontend requests

JavaScript apps often send POST, PUT, PATCH, or DELETE requests to a PHP backend.

5. Webhooks

Webhook handlers often require a specific method such as POST for security and correctness.

Take Quiz

Real Codebase Usage

In real projects, developers usually do more than just print the method. They combine request-method checks with validation, routing, and error handling.

Guard clauses

A common pattern is to reject invalid methods early.

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    exit('Method Not Allowed');
}

This keeps the rest of the code simpler.

Simple routing

A single endpoint may branch by method:

$method = $_SERVER['REQUEST_METHOD'];

switch ($method) {
    case 'GET':
        // return resource
        break;
    case 'POST':
        // create resource
        break;
    default:
        http_response_code(405);
}

Validation before processing

Developers often check both the method and the input data.

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    exit;
}

if (empty($_POST['email'])) {
    http_response_code(400);
    exit('Email is required');
}

Reading raw input for non-POST methods

In many PHP setups, PUT and DELETE data must be read manually.

if ($_SERVER['REQUEST_METHOD'] === 'PUT') {
    $body = file_get_contents('php://input');
}

Method override support

Some frameworks or apps allow a POST request to pretend to be PUT or DELETE using a hidden field or header. This is common when HTML forms cannot directly send those methods.

$method = $_SERVER['REQUEST_METHOD'];

if ($method === 'POST' && isset($_POST['_method'])) {
    $method = strtoupper($_POST['_method']);
}

This pattern should be used carefully and validated properly.

Common Mistakes

1. Using $_POST to detect the request method

Broken idea:

if ($_POST) {
    echo 'This must be POST';
}

Why it is a mistake:

  • $_POST being empty does not always mean the request was not POST
  • the correct source for the HTTP method is $_SERVER['REQUEST_METHOD']

Correct version:

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    echo 'This is a POST request';
}

2. Forgetting that method names are uppercase

Broken code:

if ($_SERVER['REQUEST_METHOD'] === 'post') {
    echo 'POST request';
}

Why it fails:

  • PHP usually provides method names like GET and POST in uppercase

Correct version:

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    echo 'POST request';
}

3. Expecting PUT data in $_POST

Broken assumption:

if ($_SERVER['REQUEST_METHOD'] === 'PUT') {
    $name = $_POST['name'];
}

Why it is a mistake:

  • $_POST is typically populated for form-encoded POST requests, not raw PUT bodies

Safer approach:

if ($_SERVER['REQUEST_METHOD'] === 'PUT') {
    $rawBody = file_get_contents('php://input');
}

4. Not handling unsupported methods

Broken code:

if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    echo 'Get data';
}

Problem:

  • other methods are silently ignored

Better version:

$method = $_SERVER['REQUEST_METHOD'];

if ($method === 'GET') {
    echo 'Get data';
} else {
    http_response_code(405);
    echo 'Method Not Allowed';
}

5. Trusting method override values without validation

If you support _method, do not accept any random value.

$method = $_SERVER['REQUEST_METHOD'];

if ($method === 'POST' && isset($_POST['_method'])) {
    $override = strtoupper($_POST['_method']);

    if (in_array($override, ['PUT', 'DELETE'], true)) {
        $method = $override;
    }
}

Comparisons

ApproachBest forNotes
if/elseif with $_SERVER['REQUEST_METHOD']Small scripts and simple logicEasy for beginners to read
switch ($_SERVER['REQUEST_METHOD'])Multiple methods on one endpointCleaner when many cases exist
Framework routingLarger applicationsFramework handles method matching for you

GET vs POST vs PUT vs DELETE

MethodTypical purposeCommon data location
GETRead dataQuery string
POSTSubmit or create dataRequest body, often in $_POST
PUTUpdate or replace dataRaw request body
DELETERemove dataSometimes raw request body, often no body

if/elseif vs switch

StyleProsCons
if/elseifSimple and flexibleCan get repetitive
switchCleaner for many exact valuesLess flexible for complex conditions

Plain PHP vs framework handling

ApproachProsCons
Plain PHPFull control, easy to learn fundamentalsMore manual work
FrameworkFaster routing and validationHides some low-level details
Take Quiz

Cheat Sheet

// Get the HTTP request method
$method = $_SERVER['REQUEST_METHOD'];

Common checks

if ($method === 'GET') {
    // read
}

if ($method === 'POST') {
    // create or submit
}

if ($method === 'PUT') {
    // update
}

if ($method === 'DELETE') {
    // delete
}

Reject unsupported methods

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    exit('Method Not Allowed');
}

Read raw body for PUT or DELETE

$body = file_get_contents('php://input');

Key rules

  • Use $_SERVER['REQUEST_METHOD'] to detect the method
  • Compare against uppercase strings like 'GET' and 'POST'
  • Do not use $_POST to detect the method
  • PUT and DELETE often require reading php://input
  • Return 405 Method Not Allowed when a method is not supported

Useful methods you may also see

  • PATCH
  • OPTIONS
  • HEAD

Common pattern

switch ($_SERVER['REQUEST_METHOD']) {
    case 'GET':
        // handle read
        break;
    case 'POST':
        // handle create
        break;
    default:
        http_response_code(405);
        echo 'Method Not Allowed';
}

FAQ

How do I check if a request is GET or POST in PHP?

Use $_SERVER['REQUEST_METHOD'] and compare it to 'GET' or 'POST'.

if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    // GET request
}

What does $_SERVER['REQUEST_METHOD'] return in PHP?

It returns the HTTP method used for the current request, such as GET, POST, PUT, or DELETE.

Can PHP detect PUT and DELETE requests?

Yes. PHP can detect them through $_SERVER['REQUEST_METHOD']. However, request body data for those methods often needs to be read from php://input.

Why is $_POST empty on a PUT request?

Because $_POST is generally populated for form-style POST requests, not for raw PUT request bodies.

Should I use if or switch to detect the request method?

Use if for simple cases and switch when handling several methods on the same endpoint.

What status code should I return for an unsupported request method?

Use 405 Method Not Allowed.

Can HTML forms send PUT or DELETE directly?

Standard HTML forms mainly support GET and POST. Many applications use method override patterns to simulate PUT or DELETE.

Take Quiz

Mini Project

Description

Build a small PHP endpoint that behaves differently depending on the HTTP request method. This demonstrates how one URL can support multiple actions, which is a common pattern in APIs and backend services.

Goal

Create a PHP script that detects GET, POST, PUT, and DELETE requests and returns an appropriate message for each one.

Requirements

  • Read the current request method using PHP.
  • Return a different response for GET, POST, PUT, and DELETE.
  • For PUT, read and display the raw request body.
  • Return a 405 status code for unsupported methods.
Take Quiz

Keep learning

Related questions

View more