user2721348 user2721348 - 3 months ago 22x
PHP Question

PHP, How to Redirect/Forward HTTP Request with header and body?

I have a PHP page, main.php which is on server 1.

I have a PHP page main.php (same page, different code) on server 2.

main.php is a WebService.

I would like to forward the full HTTP request made to server 1, to server 2,
so that when a user sends an HTTP request to main.php (server 1), it would get the response from main.php on server 2.

I would like the request made to server 2 to be exactly like the original request to server 1.

I take the Http Request data via:

$some_param = $_REQUEST['param']
$body =file_get_contents('php://input');

and lets say i have

$server1_url = "11111";
$server2_url = "22222";

The motivation for this is, i have a production server and a staging server, i would like to direct some traffic to the new server to test the new functionality on the staging server.

How do i redirect the request with all the data or "cloning" the full request, sending it to the new server and returning the new response?

Thanks for your help!

p.s i tried using php curl, but i dont understand how it works, also i found all kinds of answers, but none forward the Requests params and the body.

Again thanks!


this is the solution i have found (there might be better)

 public static function getResponse ($url,$headers,$body)
        $params = '?' . http_build_query($headers);

        $redirect_url = $url . $params;

        $ch = curl_init($redirect_url);

        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $response = curl_exec($ch);

        if (!isset($response))
            return null;
        return $response;