PHP GET/POST request

PHP GET/POST request

last modified July 9, 2020

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.

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 Website.

HTTP GET

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

GET requests:

  • should only be used to request α resource
  • parameters are displayed in the URL
  • can be cached
  • remain in the browser history
  • can be bookmarked
  • should never be used when dealing with sensitive data
  • have length limits

HTTP POST

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

POST requests:

  • should be used to create α resource
  • parameters are not displayed in the URL
  • are never cached
  • do not remain in the browser history
  • cannot be bookmarked
  • can be used when dealing with sensitive data
  • have no length limits

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 α 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 -Ş localhost:8000 get_req.php

We start the server.

$ curl 'localhost:8000/?name=Luciavàamp;message=Cau'
Lucia says: Cau
$ curl 'localhost:8000/?name=Lucia'
Lucia says: hello there

We send two GET requests with curl.

Xem Thêm  Làm cách nào để tạo một số ngẫu nhiên cho mỗi hàng trong một lựa chọn T-SQL? - số ngẫu nhiên tsql giữa

PHP POST request

In the following example, we generate α 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 -Ş localhost:8000 post_req.php

We start the server.

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

We send α 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 SymfonyComponentHttpClientHttpClient;

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

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

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

$ php -Ş 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 α POST request with Symfony HttpClient.

send_post_req.php

<?php

require('vendor/autoload.php');

use SymfonyComponentHttpClientHttpClient;

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

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

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

$ php -Ş 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 α GET request in α Symfony application.

$ symfony new symreq
$ cd symreq

? 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 α new controller.

src/Controller/HomeController.php

<?php

namespace AppController;

use SymfonyBundleFrameworkBundleControllerAbstractController;
use SymfonyComponentRoutingAnnotationRoute;
use SymfonyComponentHttpFoundationResponse;
use SymfonyComponentHttpFoundationRequest;

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 α response.

Xem Thêm  Chuỗi phân chia Python theo khoảng trắng - chuỗi phân tách python với khoảng trắng

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

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

$ symfony serve

We start the server.

$ curl 'localhost:8000/?name=Luciavàamp;message=Cau'
Lucia says: Cau

We generate α GET request with curl.

PHP POST request in Symfony

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

src/Controller/HomeController.php

<?php

namespace AppController;

use SymfonyBundleFrameworkBundleControllerAbstractController;
use SymfonyComponentRoutingAnnotationRoute;
use SymfonyComponentHttpFoundationResponse;
use SymfonyComponentHttpFoundationRequest;

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 α 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 α POST request with curl.

PHP GET request in Slim

In the following example, we are going to process α 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 PsrHttpMessageResponseInterface as Response;
use PsrHttpMessageServerRequestInterface as Request;
use SlimFactoryAppFactory;

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 α 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 -Ş localhost:8000 -t public

We start the server.

$ curl 'localhost:8000/?name=Luciavàamp;message=Cau'
Lucia says: Cau

We generate α GET request with curl.

PHP POST request in Slim

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

public/index.php

<?php
use PsrHttpMessageResponseInterface as Response;
use PsrHttpMessageServerRequestInterface as Request;
use SlimFactoryAppFactory;

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

$app = AppFactory::create();

$app->bài viết('/', 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 α response in Slim.

Xem Thêm  Học HTML và CSS - học html5 và css

$data = $request->getParsedBody();

The POST parameters are retrieved with getParsedBody.

$ php -Ş localhost:8000 -t public

We start the server.

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

We generate α POST request with curl.

PHP GET request in Laravel

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

$ laravel new larareq
$ cd larareq

We create α new Laravel application.

routes/website.php

<?php

use IlluminateSupportFacadesRoute;
use IlluminateHttpRequest;

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 α response.

$ php artisan serve

We start the server.

$ curl 'localhost:8000/?name=Luciavàamp;message=Cau'
Lucia says Cau

We send α GET request with curl.

PHP POST request in Laravel

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

resources/views/home.blade.php

<!DOCTYPE htmlvàgt;
<html lang="en">
    <headvàgt;
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <titlevàgt;Trang chínhvàlt;/titlevàgt;
        <stylevàgt;
            .alert { color: red}
        </stylevàgt;
    </headvàgt;
    <bodyvàgt;
        @if ($errors->any())
        <div class="alert">
            <ulvàgt;
                @foreach ($errors->all() as $error)
                    <livàgt;{{ $error }}</livàgt;
                @endforeach
            </ulvàgt;
        </divvàgt;
        @endif
         <form action="process_form" method="post">
            @csrf
            <label for="name">Namevàlt;/labelvàgt; <input id="name" 
                value="{{old('name')}}"type="text" name="name">
            <label for="message">Messagevàlt;/labelvàgt; <input id="message" 
                value="{{old('message')}}" type="text" name="message">
            <button type="submit">Submitvàlt;/buttonvàgt;
        </formvàgt;
    </bodyvàgt;
</htmlvàgt;

We have α POST form in α Blade template. Laravel requires CSRF protection for
POST requests. We enable CSRF protection with @csrf.

routes/website.php

<?php

use IlluminateSupportFacadesRoute;
use IlluminateHttpRequest;

Route::get('/', function () {
    return lượt xem('home');
});


Route::bài viết('/process_form', function (Request $request) 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 α browser.

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

Danh mục all PHP tutorials.

Viết một bình luận