ZetCode

PHP GET/POST request

last modified November 14, 2026

In this article, we show how to generate and process GET and POST requests in PHP. We use plain PHP and the Symfony, Slim, and Laravel frameworks. The examples were tested with PHP 8.5, Symfony 8.1, Slim 4.15, and Laravel 13.

HTTP

The Hypertext Transfer Protocol (HTTP) is an application protocol for distributed, collaborative, hypermedia information systems. HTTP is the foundation of data communication for the World Wide Web. A client sends a request that consists of a method, a URL, headers and optionally a body; the server answers with a status code, headers and a body.

HTTP GET

The HTTP GET method requests a representation of the specified resource.

GET requests:

HTTP POST

The HTTP POST method sends data to the server. It is often used when uploading a file or when submitting a completed web form.

POST requests:

A POST body is not hidden or encrypted by itself. Sensitive data must always travel over HTTPS, whichever method is used.

PHP $_GET and $_POST

PHP provides the $_GET and $_POST superglobals. The $_GET is an associative array of variables passed to the current script via the URL parameters (query string). The $_POST is an associative array of variables passed to the current script via the HTTP POST method when using application/x-www-form-urlencoded or multipart/form-data as the HTTP Content-Type in the request.

A request with another content type, such as application/json, is not parsed into $_POST; we read the raw body from the php://input stream instead. The method of the current request is available in $_SERVER['REQUEST_METHOD'].

The values come from the client and must never be trusted. We validate them, and we escape them with htmlspecialchars before we put them into an HTML page.

PHP GET request

In the following example, we generate a GET request with the curl tool and process the request in plain PHP.

get_req.php
<?php

declare(strict_types=1);

header('Content-Type: text/plain; charset=utf-8');

$name = $_GET['name'] ?? 'guest';
$message = $_GET['message'] ?? 'hello there';

echo "$name says: $message\n";

The example retrieves the name and message parameters from the $_GET variable. The null coalescing operator ?? supplies a default value when a parameter is missing; unlike a direct access, it does not raise a warning about an undefined array key.

$ php -S localhost:8000 get_req.php

We start the PHP built-in web server. The script is used as a router, so it handles every request.

We send three GET requests with curl. The parameters are separated by &, so the URL is quoted in the shell.

$ curl 'localhost:8000/?name=Lucia&message=Cau'
Lucia says: Cau
$ curl 'localhost:8000/?name=Lucia'
Lucia says: hello there
$ curl localhost:8000
guest says: hello there

PHP POST request

In the following example, we generate a POST request with the curl tool and process the request in plain PHP.

post_req.php
<?php

declare(strict_types=1);

header('Content-Type: text/plain; charset=utf-8');

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    header('Allow: POST');
    echo "Only POST is allowed\n";
    exit;
}

$name = $_POST['name'] ?? 'guest';
$message = $_POST['message'] ?? 'hello there';

echo "$name says: $message\n";

The example retrieves the name and message parameters from the $_POST variable. If the request method is not POST, we send the 405 Method Not Allowed status code with the Allow header and stop.

$ php -S localhost:8000 post_req.php

We start the server.

The -d option of curl sends the data in the request body and makes it a POST request with the application/x-www-form-urlencoded content type. The last two commands show the default value and the response to a GET request.

$ curl -d "name=Lucia&message=Cau" localhost:8000
Lucia says: Cau
$ curl -d "name=Lucia" localhost:8000
Lucia says: hello there
$ curl localhost:8000
Only POST is allowed
$ curl -s -o /dev/null -w '%{http_code}\n' localhost:8000
405

PHP form processing

In the next example, one script both displays an HTML form and processes the submitted data. The decision is based on the request method.

form.php
<?php

declare(strict_types=1);

function e(string $s): string
{
    return htmlspecialchars($s, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}

$errors = [];
$name = '';
$message = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $name = trim((string) filter_input(INPUT_POST, 'name'));
    $message = trim((string) filter_input(INPUT_POST, 'message'));

    if (mb_strlen($name) < 2) {
        $errors[] = 'Name must have at least 2 characters.';
    }

    if (mb_strlen($message) < 3) {
        $errors[] = 'Message must have at least 3 characters.';
    }

    if ($errors === []) {
        header('Content-Type: text/plain; charset=utf-8');
        echo "$name says: $message\n";
        exit;
    }

    http_response_code(400);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Message form</title>
</head>
<body>
<?php foreach ($errors as $error): ?>
    <p class="error"><?= e($error) ?></p>
<?php endforeach; ?>
    <form action="form.php" method="post">
        <label>Name <input name="name" value="<?= e($name) ?>"></label>
        <label>Message <input name="message" value="<?= e($message) ?>"></label>
        <button type="submit">Send</button>
    </form>
</body>
</html>

For a GET request, the script only displays the form. For a POST request, it reads the fields, validates them, and either prints the message or redisplays the form with error messages and status code 400.

$name = trim((string) filter_input(INPUT_POST, 'name'));

The filter_input function reads a value from the POST input and returns null when the field is missing and false when the filter fails; for an array value such as name[]=x it returns false as well. The cast to string turns both cases into an empty string, so the validation fails cleanly.

<input name="name" value="<?= e($name) ?>">

The submitted values are written back into the form so that the user does not have to retype them. The e helper wraps htmlspecialchars, which prevents cross-site scripting (XSS); without it, a value such as "><script> would break out of the attribute.

$ php -S localhost:8000 form.php

We start the server. A browser can now open http://localhost:8000/form.php.

We test the script with curl. The first request is too short and produces validation errors; the second one succeeds; the third one shows that the dangerous characters are escaped in the redisplayed form.

$ curl -si -d "name=L&message=Hi" localhost:8000/form.php | grep -E "HTTP|class=.error"
HTTP/1.1 400 Bad Request
    <p class="error">Name must have at least 2 characters.</p>
    <p class="error">Message must have at least 3 characters.</p>
$ curl -d "name=Lucia&message=Cau" localhost:8000/form.php
Lucia says: Cau
$ curl -s -d 'name=L"><script>&message=x' localhost:8000/form.php | grep 'name="name"'
        <label>Name <input name="name" value="L&quot;&gt;&lt;script&gt;"></label>

PHP send GET request with Symfony HttpClient

Symfony provides the HttpClient component which enables us to create HTTP requests in PHP.

$ composer require symfony/http-client

We install the symfony/http-client component.

send_get_req.php
<?php

declare(strict_types=1);

require __DIR__ . '/vendor/autoload.php';

use Symfony\Component\HttpClient\HttpClient;

$client = HttpClient::create();

$response = $client->request('GET', 'http://localhost:8000', [
    'query' => [
        'name' => 'Lucia',
        'message' => 'Cau',
    ],
]);

echo $response->getStatusCode(), "\n";
echo $response->getContent();

The example sends a GET request with two query parameters to the get_req.php server. The query option builds and encodes the query string for us. The getContent method returns the response body and throws an exception for 4xx and 5xx status codes.

$ php -S localhost:8000 get_req.php

We start the server in one terminal.

We run the send_get_req.php script in another terminal. It prints the status code and the body.

$ php send_get_req.php
200
Lucia says: Cau

PHP send POST request with Symfony HttpClient

In the following example, we send a POST request with Symfony HttpClient.

send_post_req.php
<?php

declare(strict_types=1);

require __DIR__ . '/vendor/autoload.php';

use Symfony\Component\HttpClient\HttpClient;

$client = HttpClient::create();

$response = $client->request('POST', 'http://localhost:8000', [
    'body' => [
        'name' => 'Lucia',
        'message' => 'Cau',
    ],
]);

echo $response->getStatusCode(), "\n";
echo $response->getContent();

The example sends a POST request with two parameters to the post_req.php server. An array passed in the body option is sent as form data (application/x-www-form-urlencoded).

$ php -S localhost:8000 post_req.php

We start the server.

We run the send_post_req.php script.

$ php send_post_req.php
200
Lucia says: Cau

PHP GET request in Symfony

In the following example, we process a GET request in a Symfony application.

$ composer create-project symfony/skeleton symreq
$ cd symreq

A new application is created with the Symfony skeleton, which contains only the framework core. Symfony 8 requires PHP 8.4 or newer.

symreq/src/Controller/HomeController.php
<?php

declare(strict_types=1);

namespace App\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Attribute\MapQueryParameter;
use Symfony\Component\Routing\Attribute\Route;

class HomeController
{
    #[Route('/', name: 'home', methods: ['GET'])]
    public function index(Request $request): Response
    {
        $name = $request->query->get('name', 'guest');
        $message = $request->query->get('message', 'hello there');

        return new Response("$name says: $message\n", Response::HTTP_OK,
            ['Content-Type' => 'text/plain']);
    }

    #[Route('/mapped', name: 'mapped', methods: ['GET'])]
    public function mapped(
        #[MapQueryParameter] string $name = 'guest',
        #[MapQueryParameter] string $message = 'hello there',
    ): Response {
        return new Response("$name says: $message\n", Response::HTTP_OK,
            ['Content-Type' => 'text/plain']);
    }
}

We create the controller by hand; the skeleton imports all controllers in the src/Controller directory automatically. The route is declared with the #[Route] attribute; it replaces the docblock annotations used in older Symfony versions.

$name = $request->query->get('name', 'guest');

The GET parameter is retrieved with $request->query->get. The second parameter of the method is a default value which is used when no value was sent.

#[MapQueryParameter] string $name = 'guest',

The second action shows an alternative. The #[MapQueryParameter] attribute injects a query parameter directly into an argument; Symfony converts it to the declared type and uses the default value when the parameter is missing. If the parameter has the wrong type, such as an array for a string, Symfony responds with 404.

$ php -S localhost:8000 -t public

We start the server. For development, the symfony serve command of the Symfony CLI can be used instead.

We generate three GET requests with curl.

$ curl 'localhost:8000/?name=Lucia&message=Cau'
Lucia says: Cau
$ curl localhost:8000
guest says: hello there
$ curl 'localhost:8000/mapped?name=Lucia'
Lucia says: hello there

PHP POST request in Symfony

In the following example, we process a POST request in a Symfony application.

symreq/src/Controller/MessageController.php
<?php

declare(strict_types=1);

namespace App\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;

class MessageController
{
    #[Route('/message', name: 'message', methods: ['POST'])]
    public function create(Request $request): Response
    {
        $name = $request->getPayload()->get('name', 'guest');
        $message = $request->getPayload()->get('message', 'hello there');

        return new Response("$name says: $message\n", Response::HTTP_OK,
            ['Content-Type' => 'text/plain']);
    }
}

We add a controller that accepts only POST requests on the /message route.

$name = $request->getPayload()->get('name', 'guest');

The POST parameter is retrieved with getPayload. It returns the form fields of a form-encoded request and the decoded data of a JSON request, so the same code handles both. The older $request->request->get reads form fields only. The second parameter of the method is a default value.

$ php -S localhost:8000 -t public

We start the server.

We generate two POST requests with curl, and a GET request to the same URL. The router answers it with 405, because the route accepts only POST.

$ curl -d "name=Lucia" localhost:8000/message
Lucia says: hello there
$ curl -d "name=Lucia&message=Cau" localhost:8000/message
Lucia says: Cau
$ curl -s -o /dev/null -w '%{http_code}\n' localhost:8000/message
405

PHP GET and POST requests in Slim

In the following example, we process GET and POST requests in the Slim framework.

$ composer require slim/slim slim/psr7

We install the slim/slim framework and the slim/psr7 implementation of the PSR-7 HTTP message interfaces.

public/index.php
<?php

declare(strict_types=1);

use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Slim\Factory\AppFactory;

require __DIR__ . '/../vendor/autoload.php';

$app = AppFactory::create();
$app->addBodyParsingMiddleware();
$app->addRoutingMiddleware();
$app->addErrorMiddleware(true, true, true);

$app->get('/', function (Request $request, Response $response): Response {

    $params = $request->getQueryParams();

    $name = $params['name'] ?? 'guest';
    $message = $params['message'] ?? 'hello there';

    $response->getBody()->write("$name says: $message\n");

    return $response->withHeader('Content-Type', 'text/plain');
});

$app->post('/', function (Request $request, Response $response): Response {

    $data = (array) $request->getParsedBody();

    $name = $data['name'] ?? 'guest';
    $message = $data['message'] ?? 'hello there';

    $response->getBody()->write("$name says: $message\n");

    return $response->withHeader('Content-Type', 'text/plain');
});

$app->run();

We define one route for each method. Slim 4 uses the standard PSR-7 interfaces, so the same code style works with other PSR-7 frameworks.

$params = $request->getQueryParams();

The query parameters are retrieved with getQueryParams, which returns an array. We provide defaults with the ?? operator.

$app->addBodyParsingMiddleware();
$data = (array) $request->getParsedBody();

The POST parameters are retrieved with getParsedBody. This works only after the body parsing middleware has been added; it decodes form data and JSON. Without a body, getParsedBody returns null, so we cast the result to an array.

$response->getBody()->write("$name says: $message\n");

We write the output to the response body with write. PSR-7 messages are immutable, so withHeader returns a new response.

$ php -S localhost:8000 -t public

We start the server.

We send two GET and three POST requests with curl; the last one posts JSON, which the body parsing middleware understands.

$ curl 'localhost:8000/?name=Lucia&message=Cau'
Lucia says: Cau
$ curl localhost:8000
guest says: hello there
$ curl -d "name=Lucia" localhost:8000
Lucia says: hello there
$ curl -d "name=Lucia&message=Cau" localhost:8000
Lucia says: Cau
$ curl -H "Content-Type: application/json" -d '{"name":"Lucia","message":"Cau"}' localhost:8000
Lucia says: Cau

PHP GET request in Laravel

In the following example, we process a GET request in Laravel.

$ composer create-project laravel/laravel larareq
$ cd larareq

We create a new Laravel application. Alternatively, we can use the laravel new command of the Laravel installer.

larareq/routes/web.php
<?php

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

Route::get('/hello', function (Request $request) {

    $name = $request->query('name', 'guest');
    $message = $request->query('message', 'hello there');

    return response("$name says: $message\n")
        ->header('Content-Type', 'text/plain');
});

Route::get('/message', function () {
    return view('message');
});

Route::post('/message', function (Request $request) {

    $validated = $request->validate([
        'name' => 'required|min:2',
        'message' => 'required|min:3',
    ]);

    $name = $validated['name'];
    $message = $validated['message'];

    return response("$name says: $message\n")
        ->header('Content-Type', 'text/plain');
});

We define routes in the routes/web.php file; this listing also contains the two POST-related routes that we use in the next section. The /hello route reads the query parameters with the query method of the injected Request; the second parameter is a default value.

$ php artisan serve

We start the development server; it listens on port 8000 by default.

We send two GET requests with curl.

$ curl 'localhost:8000/hello?name=Lucia&message=Cau'
Lucia says: Cau
$ curl localhost:8000/hello
guest says: hello there

PHP POST request in Laravel

In the following example, we send a POST request from an HTML form.

larareq/resources/views/message.blade.php
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Message form</title>
    <style>
        .alert { color: red; }
    </style>
</head>
<body>
    @if ($errors->any())
    <div class="alert">
        <ul>
            @foreach ($errors->all() as $error)
                <li>{{ $error }}</li>
            @endforeach
        </ul>
    </div>
    @endif

    <form action="/message" method="post">
        @csrf
        <label for="name">Name</label>
        <input id="name" type="text" name="name" value="{{ old('name') }}">
        <label for="message">Message</label>
        <input id="message" type="text" name="message" value="{{ old('message') }}">
        <button type="submit">Submit</button>
    </form>
</body>
</html>

We have a POST form in a Blade template. Laravel requires CSRF protection for POST requests. We enable CSRF protection with @csrf, which adds a hidden _token field. The {{ }} syntax escapes the output, and old returns the previously submitted value after a failed validation.

Route::post('/message', function (Request $request) {

    $validated = $request->validate([
        'name' => 'required|min:2',
        'message' => 'required|min:3',
    ]);
    ...

The POST route in the routes/web.php file (see the listing above) validates the input. When the validation fails, Laravel redirects back to the form and fills the $errors variable. When it succeeds, we receive only the validated fields. This example is best tested in a browser at http://localhost:8000/message.

Without a browser, we have to play the part of the form: we fetch the form to get a session cookie and a token, and then send the token with the POST request. The first request has no token, and Laravel rejects it with the status code 419. The last request fails validation (the values are too short), and Laravel redirects back to the form.

$ curl -s -o /dev/null -w '%{http_code}\n' -d 'name=Lucia&message=Cau' localhost:8000/message
419
$ TOKEN=$(curl -s -c jar.txt localhost:8000/message | grep -o 'name="_token" value="[^"]*"' | cut -d'"' -f4)
$ curl -s -b jar.txt -d "_token=$TOKEN&name=Lucia&message=Cau" localhost:8000/message
Lucia says: Cau
$ curl -s -o /dev/null -w '%{http_code} %{redirect_url}\n' -b jar.txt -c jar.txt -d "_token=$TOKEN&name=L&message=Hi" localhost:8000/message
302 http://localhost:8000/message

Source

PHP manual: $_GET

PHP manual: $_POST

Symfony routing, Slim 4 documentation, and Laravel routing

In this article, we have worked with GET and POST requests in plain PHP, Symfony, Slim, and Laravel. We have also sent requests with the Symfony HttpClient component. See also the PHP superglobals, PHP JSON and PHP sessions and cookies tutorials.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all PHP tutorials.