Tutorial – Creating a PHP Reverse Proxy

I spent so much time researching how to create a reverse proxy in PHP so that I could solve a problem. No matter what your reason, if you need a reverse proxy for PHP here is a simple one you can implement.

For this proxy, you will need to install the following dependencies:

The code:

<?php

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

use \GuzzleHttp\Client;
use \GuzzleHttp\Psr7\Request;
use \Narrowspark\HttpEmitter\SapiEmitter;

// configure the remote server
$remoteServer = 'http://localhost:8000';

// setup the request
$requestBody = file_get_contents('php://input');
$httpClient = new Client();
$request = new Request(
    $_SERVER['REQUEST_METHOD'],
    $remoteServer . $_SERVER['REQUEST_URI'],
    getallheaders(),
    $requestBody
);

try {
    // try to obtain a response
    $response = $httpClient->send($request, [
        'allow_redirects' => false
    ]);
    $emitter = new SapiEmitter();
    $emitter->emit($response);
} catch (\Exception $e) {
    // send back 404 if there was an issue getting a response
    http_response_code(404);
}

Or you can directly download it from https://github.com/ua1-labs/php-proxy

Leave a Reply