Skip to content

Instantly share code, notes, and snippets.

@thiagomarini
Last active August 7, 2021 16:34
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thiagomarini/a374c27599898fcae3bb98928306e36a to your computer and use it in GitHub Desktop.
Save thiagomarini/a374c27599898fcae3bb98928306e36a to your computer and use it in GitHub Desktop.
Plain PHP Curl proxy script example for json APIs. I tried using Apache mod_proxy for that but it was returning 301 only on curl, on guzzle it was fine.
<?php
// Needs to be used with a .htaccess file pointing all requests to it
$uri = $_SERVER['REQUEST_URI'];
$queryString = http_build_query($_GET);
$payload = file_get_contents('php://input');
$url = 'https://foo.bar' . $uri;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $_SERVER['REQUEST_METHOD']);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($payload)
));
if($payload) {
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
}
$response = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
header('Status:', true, $status);
header('Content-Type: application/json');
echo $response;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment