What’s the best way to sanitize the callback for jsonp?
I currently have something like:
function api_output($data) {
if (isset($_GET['callback'])) {
$cb = preg_replace("/[^][.\\'\\\"_A-Za-z0-9]/", '', $_GET['callback']);
send_js_headers();
print sprintf('%s(%s);', $cb, json_encode($data));
exit(0);
}
send_json_headers();
echo json_encode($data);
exit(0);
}
Why? :
Do I need to sanitize the callback parameter from a JSONP call?
The callback must be a valid javascript identifier, and your server side code should verify this. Javascript identifiers can only contain alphabets, numbers, underscore and $ symbol.
As long as the callback name is a valid JS identifier, you don’t need to encode/escape it. And if the callback isn’t a valid identifier, you should simply return a 400 error code.
You must NOT replace characters in the callback name. There just isn’t any point in doing so, because the client code will no longer have the callback function defined.