Last active
March 12, 2018 19:35
-
-
Save jcward/9b3fa893bc43ae855add65a36aaffa5e to your computer and use it in GitHub Desktop.
A PHP JSONP proxy script
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) { | |
. . . | |
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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