Skip to content

Instantly share code, notes, and snippets.

@lightsfury
Created May 29, 2012 03:55
Show Gist options
  • Select an option

  • Save lightsfury/2822425 to your computer and use it in GitHub Desktop.

Select an option

Save lightsfury/2822425 to your computer and use it in GitHub Desktop.
Serve JSONP in php
<?php
header('Content-type: application/javascript; charset=utf-8');
function getJSON($path)
{
return file_get_contents($path);
}
function getJSONP($path, $callback)
{
return sprintf("%s(%s);", $callback, getJSON($path));
}
if (!isset($_SERVER['PATH_TRANSLATED']))
{
// Attempting to call this file manually
header('HTTP/1.1 404 Not Found');
}
$path = $_SERVER['PATH_TRANSLATED'];
// Check for a malicious attempt to read a non-JSON file
if (!preg_match('/\.json$/i', $path))
{
header('HTTP/1.1 404 Not Found');
die();
}
// Check for a malicious attempt to read outside the document root
$documentRoot = str_replace('/', '\\/', $_SERVER['DOCUMENT_ROOT']);
$documentRegex = sprintf('/^%s/', $documentRoot);
if (!preg_match($documentRegex, $path))
{
header('HTTP/1.1 404 Not Found');
die();
}
// Make sure the file exists
if (!is_file($path))
{
header('HTTP/1.1 404 Not Found');
die();
}
if (isset($_GET['callback']))
{
// Serving JSONP (JSON+callback)
$data = getJSONP($path, $_GET['callback']);
}
else
{
// Serving JSON
$data = getJSON($path);
}
echo $data;
die();
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment