ZetCode

PHP GET/POST request

last modified January 10, 2023

PHP GET/POST request tutorial shows how to generate and process GET and POST requests in PHP. We use plain PHP and Symfony, Slim, and Laravel frameworks.

$ php -v
php -v
PHP 8.1.2 (cli) (built: Aug  8 2022 07:28:23) (NTS)
...

We use PHP version 8.1.2.

HTTP

The Hypertext Transfer Protocol (HTTP) is an application protocol for distributed, collaborative, hypermedia information systems. HTTP protocol is the foundation of data communication for the World Wide Web.

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:

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.

PHP GET request

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

get_req.php
<?php

$name = $_GET['name'];

if ($name == null) {
    $name = 'guest';
}

$message = $_GET['message'];

if ($message == null) {
    $message = 'hello there';
}

echo "$name says: $message";

The example retrieves the name and message parameters from the $_GET variable.

$ php -S localhost:8000 get_req.php

We start the server.

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

We send two GET requests with curl.

PHP POST request

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

post_req.php
<?php

$name = $_POST['name'];

if ($name == null) {
    $name = 'guest';
}

$message = $_POST['message'];

if ($message == null) {
    $message = 'hello there';
}


echo "$name says: $message";

The example retrieves the name and message parameters from the $_POST variable.

$ php -S localhost:8000 post_req.php

We start the server.

$ curl -d "name=Lucia&message=Cau" localhost:8000
Lucia says: Cau

We send a POST request with curl.

PHP send GET request with Symfony HttpClient

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

$ composer req symfony/http-client

We install the symfony/http-client component.

send_get_req.php
<?php

require('vendor/autoload.php');

use Symfony\Component\HttpClient\HttpClient;

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

$content = $response->getContent();
echo $content . "\n";

The example sends a GET request with two query parameters to localhost:8000/get_request.php.

$ php -S localhost:8000 get_req.php

We start the server.

$ php send_get_req.php 
Lucia says: Cau

We run the send_get_req.php script.

PHP send POST request with Symfony HttpClient

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

send_post_req.php
<?php

require('vendor/autoload.php');

use Symfony\Component\HttpClient\HttpClient;

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

$content = $response->getContent();
echo $content . "\n";

The example sends a POST request with two parameters to localhost:8000/post_req.php.

$ php -S localhost:8000 post_req.php

We start the server.

$ php send_post_req.php 
Lucia says: Cau

We run the send_post_req.php script.

PHP GET request in Symfony

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

$ symfony new symreq
$ cd symreq

A new application is created.

$ composer req annot
$ composer req maker --dev

We install the annot and maker components.

$ php bin/console make:controller HomeController

We create a new controller.

src/Controller/HomeController.php
<?php

namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;

class HomeController extends AbstractController
{
    /**
     * @Route("/", name="home", methods={"GET"})
     */
    public function index(Request $request): Response
    {
        $name = $request->query->get('name', 'guest');
        $message = $request->query->get('message', 'hello there');

        $output = "$name says: $message";

        return new Response($output, Response::HTTP_OK,
            ['content-type' => 'text/plain']);
    }
}

Inside the HomeController's index method, we get the query parameters and create a response.

$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 retrieved.

$ symfony serve

We start the server.

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

We generate a GET request with curl.

PHP POST request in Symfony

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

src/Controller/HomeController.php
<?php

namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;

class HomeController extends AbstractController
{
    /**
     * @Route("/", name="home", methods={"POST"})
     */
    public function index(Request $request): Response
    {
        $name = $request->request->get('name', 'guest');
        $message = $request->request->get('message', 'hello there');

        $output = "$name says: $message";

        return new Response($output, Response::HTTP_OK,
            ['content-type' => 'text/plain']);
    }
}

We change the controller to process the POST request.

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

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

$ symfony serve

We start the server.

$ curl -d "name=Lucia" localhost:8000
Lucia says: hello there

We generate a POST request with curl.

PHP GET request in Slim

In the following example, we are going to process a GET request in the Slim framework.

$ composer req slim/slim
$ composer req slim/psr7
$ composer req slim/http

We install slim/slim, slim/psr7, and slim/http packages.

public/index.php
<?php
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->get('/', function (Request $request, Response $response): Response {

    $name = $request->getQueryParam('name', 'guest');
    $message = $request->getQueryParam('message', 'hello there');
    $output = "$name says $message";

    $response->getBody()->write($output);
    return $response;
});

$app->run();

We get the parameters and return a response in Slim.

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

The query parameter is retrieved with getQueryParam; the second parameter is the default value.

$response->getBody()->write($output);

We write the output to the response body with write.

$ php -S localhost:8000 -t public

We start the server.

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

We generate a GET request with curl.

PHP POST request in Slim

In the following example, we are going to process a POST request in the Slim framework.

public/index.php
<?php
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->post('/', function (Request $request, Response $response): Response {

    $data = $request->getParsedBody();
    
    $name = $data['name'];
    $message = $data['message'];

    if ($name == null) {
        $name = 'guest';
    }

    if ($message == null) {
        $message = 'hello there';
    }
    
    $output = "$name says: $message";

    $response->getBody()->write($output);
    return $response;
});

$app->run();

We get the POST parameters and return a response in Slim.

$data = $request->getParsedBody();

The POST parameters are retrieved with getParsedBody.

$ php -S localhost:8000 -t public

We start the server.

$ curl -d "name=Lucia" localhost:8000
Lucia says: hello there

We generate a POST request with curl.

PHP GET request in Laravel

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

$ laravel new larareq
$ cd larareq

We create a new Laravel application.

routes/web.php
<?php

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

Route::get('/', function (Request $request) {
    
    $name = $request->query('name', 'guest');
    $message = $request->query('message', 'hello there');
    $output = "$name says $message";

    return $output;
});

We get the GET parameters and create a response.

$ php artisan serve

We start the server.

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

We send a GET request with curl.

PHP POST request in Laravel

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

resources/views/home.blade.php
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Home page</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="process_form" method="post">
            @csrf
            <label for="name">Name</label> <input id="name" 
                value="{{old('name')}}"type="text" name="name">
            <label for="message">Message</label> <input id="message" 
                value="{{old('message')}}" type="text" name="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.

routes/web.php
<?php

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

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


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

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

    return $output;
});

We validate and retrieve the POST parameters and send them in the response. This example should be tested in a browser.

In this article we have worked with GET and POST requests in plain PHP, Symfony, Slim, and Laravel.

Author

My name is Jan Bodnar and I am a passionate programmer with many years of programming experience. I have been writing programming articles since 2007. So far, I have written over 1400 articles and 8 e-books. I have over eight years of experience in teaching programming.

List all PHP tutorials.