Skip to content

Instantly share code, notes, and snippets.

@wgbartley
Last active December 18, 2017 16:30
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save wgbartley/11337650 to your computer and use it in GitHub Desktop.
Save wgbartley/11337650 to your computer and use it in GitHub Desktop.
Spark PHP Proxy
<?php
// Set your access token here
define('ACCESS_TOKEN', 'your_access_token_here');
// Make sure we have an HTTP_ACCEPT header,
// and if so, make it lower-case for easier string matching
if(isset($_SERVER['HTTP_ACCEPT']))
$_SERVER['HTTP_ACCEPT'] = strtolower($_SERVER['HTTP_ACCEPT']);
else
$_SERVER['HTTP_ACCEPT'] = '';
// Build the URL. Since it's possible to accidentally have an
// extra / or two in $_SERVER['QUERY_STRING], replace "//" with "/"
// using str_replace(). This also appends the access token to the URL.
$url = 'https://'.str_replace('//', '/', 'api.spark.io/'.$_SERVER['QUERY_STRING'].'?access_token='.ACCESS_TOKEN);
// Check to see if we want to monitor an SSE stream
if($_SERVER['HTTP_ACCEPT']=='text/event-stream') {
// Requisite response headers
header('Content-type: text/event-stream');
header('Cache-control: no-cache');
// Open the URL
$sse = fopen($url, 'r');
// Loop until the server stops sending us data
while(!feof($sse)) {
// Output the data
echo trim(fgets($sse)).PHP_EOL;
echo PHP_EOL;
// Force a flush to the browser
ob_flush();
flush();
}
// All's well that ends well?
fclose($sse);
exit;
} else {
// Most everything else should be JSON
header('Content-type: application/json');
// HTTP GET requests are easy!
if(strtoupper($_SERVER['REQUEST_METHOD'])=='GET')
echo file_get_contents($url);
// HTTP POST requires the use of cURL
elseif (strtoupper($_SERVER['REQUEST_METHOD'])=='POST') {
$c = curl_init();
curl_setopt_array($c, array(
// Set the URL to access
CURLOPT_URL => $url,
// Tell cURL it's an HTTP POST request
CURLOPT_POST => TRUE,
// Include the POST data
// $HTTP_RAW_POST_DATA may work on some servers, but it's deprecated in favor of php://input
CURLOPT_POSTFIELDS => file_get_contents('php://input'),
// Return the output to a variable instead of automagically echoing it (probably a little redundan$
CURLOPT_RETURNTRANSFER => TRUE
));
// Make the cURL call and echo the response
echo curl_exec($c);
// Close the cURL resource
curl_close($c);
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment