Skip to content

Instantly share code, notes, and snippets.

@westonwatson
Last active May 6, 2019 18:07
Show Gist options
  • Save westonwatson/bc436c61015a1ef3da7d614e1e751daf to your computer and use it in GitHub Desktop.
Save westonwatson/bc436c61015a1ef3da7d614e1e751daf to your computer and use it in GitHub Desktop.
Make cross-domain requests with AJAX using this proxy.php script.
<?php
/* AJAX Proxy Script */
const TARGET_HEADER_KEYS = ['ACTION', 'METHOD'];
const ALLOWED_METHODS = ['POST', 'GET'];
// Grab Request Target from Headers
$headers = getallheaders();
//Validate Request Headers
foreach (TARGET_HEADER_KEYS as $key) {
if (empty($headers[$key])) {
die("'{$key}' Request Header is Required!");
}
}
//Define Request
$action = $headers[TARGET_HEADER_KEYS[0]];
$method = $headers[TARGET_HEADER_KEYS[1]];
//Pass along some browser info
$user_agent = $headers['User-Agent'];
$accept_encoding = $headers['Accept-Encoding'];
$ch = curl_init();
switch($method) {
case ALLOWED_METHODS[0]:
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $_POST);
break;
case ALLOWED_METHODS[1]:
//set specific method options
break;
default:
die("'{$method}' Is Not A Supported HTTP Request Type!");
}
curl_setopt($ch, CURLOPT_URL, $action);
curl_setopt($ch, CURLOPT_USERAGENT, $user_agent);
curl_setopt($ch, CURLOPT_ACCEPT_ENCODING, $accept_encoding);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 24);
curl_setopt($ch, CURLOPT_TIMEOUT, 25);
$data = curl_exec($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
http_response_code($httpcode);
echo $data;
exit;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment