Skip to content

Instantly share code, notes, and snippets.

@x0x8x
Forked from jcward/JSONProxy.php
Created March 12, 2018 19:35
Show Gist options
  • Save x0x8x/69896b11952a1dda214a0f1681a451eb to your computer and use it in GitHub Desktop.
Save x0x8x/69896b11952a1dda214a0f1681a451eb to your computer and use it in GitHub Desktop.
A PHP JSONP proxy script
Want to fetch JSON from cross-origin and it doesn't serve JSONP?
One solution is a proxy PHP script that will fetch the JSON and
return it as JSONP.
As a pre-requisite, your server must have PHP and PHP-curl installed:
e.g.
- sudo apt-get install libapache2-mod-php5 php5-curl
- sudo /etc/init.d/apache2 restart
Example usage with jQuery:
var data_url = "http://dataserver/data.json";
S.getJSON('http://proxyserver/JSONProxy.php?callback=?&src='+data_url, function(data) {
. . .
});
<?php header('content-type: application/json; charset=utf-8');
# Curl / proxy parts of this script from:
# https://webster.cs.washington.edu/course-website/16au/lectures/slides/proxy.phps
$url = $_GET['src'];
$data = array();
# Open the cURL session
$curlSession = curl_init();
curl_setopt($curlSession, CURLOPT_URL, $url);
curl_setopt($curlSession, CURLOPT_HEADER, 1);
curl_setopt($curlSession, CURLOPT_RETURNTRANSFER,1);
curl_setopt($curlSession, CURLOPT_TIMEOUT,30);
curl_setopt($curlSession, CURLOPT_SSL_VERIFYHOST, 1);
# Send the request and store the result in an array
$response = curl_exec ($curlSession);
# Check that a connection was made
if (curl_error($curlSession)){
# If it wasn't...
print curl_error($curlSession);
} else {
#clean duplicate header that seems to appear on fastcgi with output buffer on some servers!!
$response = str_replace("HTTP/1.1 100 Continue\r\n\r\n","",$response);
$ar = explode("\r\n\r\n", $response, 2);
$header = $ar[0];
$body = $ar[1];
$data = $body;
}
# Output the JSONP callback with data
echo $_GET['callback'] . '('.json_encode($data).')';
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment