Last active
August 7, 2021 16:34
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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