Created
May 29, 2012 03:55
-
-
Save lightsfury/2822425 to your computer and use it in GitHub Desktop.
Serve JSONP in php
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/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