There’s at least a half dozen PHP proxies/wrappers in the forums already, but I wanted one that was a little more flexible. This one should take whatever GET or POST request you throw at it, append your access token, and then pass it on to the Spark Cloud. The code is pasted below, but is also tracked in this gist.
<UPDATE> I have added an updated version that’s a little more transparent if you are using Apache mod_rewrite. </UPDATE>
proxy.php without Apache mod_rewrite:
<?
// Set your access token here
define('ACCESS_TOKEN', 'your_access_token_here');
// All responses should be JSON
header('Content-type: application/json');
// Security check!
if(!isset($_SERVER['HTTP_REFERER']) || substr_count($_SERVER['HTTP_REFERER'], $_SERVER['SERVER_NAME'])==0)
die(json_encode(array(
'error' => 'Invalid request'
)));
// 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/v1/devices/'.$_SERVER['QUERY_STRING'].'?access_token='.ACCESS_TOKEN);
// 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 redundant)
CURLOPT_RETURNTRANSFER => TRUE
));
// Make the cURL call and echo the response
echo curl_exec($c);
// Close the cURL resource
curl_close($c);
}
?>
Time for an example! I’m going to assume you name the file proxy.php
and put it in the root of your web directory (/proxy.php
). Also, make sure you change the define('ACCESS_TOKEN', 'your_access_token_here');
to match your access token.
Simple Ajax GET and POST requests using jQuery might look something like this:
var CORE_ID = 'your_core_id';
$.get('/proxy.php?'+CORE_ID+'/variable_name', function(response) {
console.log(response);
});
$.post('/proxy.php?'+CORE_ID+'/function_name', {'args': 'function_arguments'}, function(response) {
console.log(response);
});
If you want to make the Ajax calls a little less awkward, you can use Apache’s mod_rewrite to make the URLs a little more transparent. Instead of making calls to /path/to/proxy.php?YOUR_CORE_ID/yourVariableOrFunction
, you can use it almost exactly like you use the real cloud API like /v1/devices/YOUR_CORE_ID/yourVariableOrFunction
.
proxy.php with Apache mod_rewrite:
<?
define('ACCESS_TOKEN', 'your_access_token_here');
header('Content-type: application/json');
// Security check!
if(!isset($_SERVER['HTTP_REFERER']) || substr_count($_SERVER['HTTP_REFERER'], $_SERVER['SERVER_NAME'])==0)
die(json_encode(array(
'error' => 'Invalid request'
)));
$url = 'https://api.spark.io'.$_SERVER['REQUEST_URI'].'?access_token='.ACCESS_TOKEN;
if(strtoupper($_SERVER['REQUEST_METHOD'])=='GET')
echo file_get_contents($url);
elseif (strtoupper($_SERVER['REQUEST_METHOD'])=='POST') {
$c = curl_init();
curl_setopt_array($c, array(
CURLOPT_URL => $url,
CURLOPT_POST => TRUE,
CURLOPT_POSTFIELDS => file_get_contents('php://input'),
CURLOPT_RETURNTRANSFER => TRUE
));
echo curl_exec($c);
curl_close($c);
}
?>
.htaccess:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule ^proxy\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . proxy.php [L]
</IfModule>
And here’s what those jQuery Ajax examples would look like using the mod_rewrite version:
var CORE_ID = 'your_core_id';
$.get('/v1/devices/'+CORE_ID+'/variable_name', function(response) {
console.log(response);
});
$.post('/v1/devices/'+CORE_ID+'/function_name', {'args': 'function_arguments'}, function(response) {
console.log(response);
});
^-- That looks familiar, doesn’t it? --^
I hope someone finds this useful. I swear I’ve written this thing 3+ 4+ times and keep losing it or deleting it as I build new projects and delete old ones!