Routing HTTP (API) Calls via PHP

98 views Asked by At

Is there a way to "route" HTTP (API) calls via PHP? Basically I have 3 systems. System A can reach system B and System B can reach System C. However, system A cannot reach system C. Is there an easy to route my API calls to System B which can act as a the middleman and communicate with System C and then B can respond to A with the call result?

1

There are 1 answers

0
lxg On

What you’re trying to create is a proxy. This can very well done with PHP. The following code is a very simple implementation of a proxy, reading POST data, submitting them to a different URL, and returning the result to the original client:

$targetUrl = 'https://www.example.com/api/foobar';
$headers = [];
$postData = file_get_contents('php://input');

foreach ($_SERVER as $key => $value)
{
    if (stripos($key, "HTTP_") === 0 && stripos($key, "Host") === false)
    {
        $key = str_replace(" ", "-", ucwords(strtolower(str_replace("_"," ",substr($key,5)))));
        $headers[] = "$key: $value";
    }
}

$curl = curl_init();

curl_setopt($curl, CURLOPT_URL, $targetUrl);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_VERBOSE, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($curl, CURLOPT_MAXREDIRS, 5);
curl_setopt($curl, CURLOPT_POSTFIELDS, $postData);

$response = curl_exec($curl);

if (curl_errno($curl))
    throw new \Exception(sprintf("Connection error %s: %s", curl_errno($curl), curl_error($curl)));

curl_close($curl);

echo gzdecode($response);

This is just an example, and it makes several assumitions (payload is POST data, response is gzipped, etc.)

Feel free to adapt the code to your needs, or have a look at various more advanced implementations of PHP-based proxies, e.g. https://github.com/jenssegers/php-proxy.