Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
<?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
You can’t perform that action at this time.