Skip to content

Instantly share code, notes, and snippets.

@bobagold
Created January 19, 2016 09:10
Show Gist options
  • Save bobagold/0476a27973c8ac427101 to your computer and use it in GitHub Desktop.
Save bobagold/0476a27973c8ac427101 to your computer and use it in GitHub Desktop.
function httpProxy($request, $upstream, Closure $callback = null)
{
$requestHeaders = $request['headers'];
unset($requestHeaders['Host'], $requestHeaders['Connection']);
$requestHeaders = stringifyHeaderPairs($requestHeaders);
$ch = curl_init($upstream . $request['uri']);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $request['method']);
if ($request['method'] === 'POST') {
curl_setopt($ch, CURLOPT_POSTFIELDS, file_get_contents($request['contentsFile']));
}
curl_setopt($ch, CURLOPT_HTTPHEADER, $requestHeaders);
$response = curl_exec($ch);
$responseHeadersSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$responseHeaders = substr($response, 0, $responseHeadersSize);
$headers = array_filter(explode("\r\n", $responseHeaders));
$body = substr($response, $responseHeadersSize);
if ($callback) {
list ($body, $headers) = $callback($body, $headers);
}
$headerPairs = headerPairs($headers);
unset($headerPairs['Transfer-Encoding']);
foreach (stringifyHeaderPairs($headerPairs) as $header) {
header($header, true);
}
echo $body;
}
function headerPairs($headers)
{
$headerPairs = [];
foreach ($headers as $i => $header) {
$pair = explode(': ', $header, 2);
if (count($pair) === 1) {
array_unshift($pair, $i);
}
$headerPairs[$pair[0]] = $pair[1];
}
return $headerPairs;
}
function stringifyHeaderPairs($headers)
{
array_walk($headers, function (&$value, $key) {
$value = is_int($key) ? $value : "$key: $value";
});
$headers = array_values($headers);
return $headers;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment