Skip to content

Instantly share code, notes, and snippets.

@nicocrm
Last active May 9, 2019 04:36
Show Gist options
  • Save nicocrm/220511f18f64b4321ba371113c0bf687 to your computer and use it in GitHub Desktop.
Save nicocrm/220511f18f64b4321ba371113c0bf687 to your computer and use it in GitHub Desktop.
<?php
// Execute with php -S 0.0.0.0:3000 to serve API
// And point the client to http://localhost:3000/cors-proxy.php/api
//
$path = $_SERVER['PATH_INFO'];
$base_url = MY_BASE_URL;
$url = $base_url . $path;
if(isset($_SERVER["QUERY_STRING"])) {
$url = $url . '?' . $_SERVER["QUERY_STRING"];
}
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: *');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS, PATCH, PUT');
if ( strtolower($_SERVER['REQUEST_METHOD']) == 'options' ) {
exit();
}
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $_SERVER['REQUEST_METHOD']);
$request_body = file_get_contents('php://input');
if ($request_body) {
curl_setopt( $ch, CURLOPT_POSTFIELDS, $request_body );
}
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_HEADER, true );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true );
$headers = [];
if(isset($_SERVER["CONTENT_TYPE"])) {
$headers[] = 'Content-Type: ' . $_SERVER["CONTENT_TYPE"];
}
foreach($_SERVER as $name => $val) {
if(stripos($name, 'HTTP_X') === 0) {
$key = str_replace('HTTP_', '', $name);
$key = str_replace('_', '-', $key);
$headers[] = "$key: $val";
}
}
if($headers) {
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
}
list($header, $contents) = preg_split( '/([\r\n][\r\n])\\1/', curl_exec( $ch ), 2 );
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
http_response_code($httpcode);
$header_text = preg_split( '/[\r\n]+/', $header );
foreach($header_text as $header) {
// error_log($header);
if(stripos($header, 'Content-Type') === 0
|| stripos($header, 'X-') === 0) {
header($header);
}
}
print($contents);
print("\n");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment