Skip to content

Instantly share code, notes, and snippets.

@joshbuchea
Forked from mathiasbynens/jsonp.php
Created July 8, 2014 20:40
Show Gist options
  • Save joshbuchea/4cd56c18b4385f6f0633 to your computer and use it in GitHub Desktop.
Save joshbuchea/4cd56c18b4385f6f0633 to your computer and use it in GitHub Desktop.
<?php
// Note: The user-provided callback name must be filtered to prevent attack
// vectors. This script simply removes any symbols other than `[a-zA-Z0-9$_]`
// from the input. Sadly, this blocks the use of some valid JavaScript
// identifiers, and also accepts a few invalid ones. See
// http://mathiasbynens.be/notes/javascript-identifiers for details.
$callback = isset($_GET['callback'])
? preg_replace('/[^a-zA-Z0-9$_.]/s', '', $_GET['callback'])
: false;
// Send the appropriate MIME type: JSON or JSON-P/JavaScript?
header('Content-Type: ' .
($callback ? 'application/javascript' : 'application/json') .
';charset=UTF-8');
// There’s no reason not to allow CORS for public APIs.
// See http://annevankesteren.nl/2012/12/cors-101 for details.
header('Access-Control-Allow-Origin: *');
// Your data goes here
$data = array('some-key' => 'some-value');
// Output the end result
echo ($callback ? $callback . '(' : '') .
json_encode($data, JSON_UNESCAPED_SLASHES) . // ≥ PHP 5.4.0
($callback ? ')' : '');
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment