views:

101

answers:

2
<?php header('content-type: application/json');

$json = json_encode($data);

echo isset($_GET['callback'])
    ? "{$_GET['callback']}($json)"
    : $json;

Or should I for example filter the $_GET['callback'] variable so that it only contains a valid JavaScript function name? If so, what are valid JavaScript function names?

Or is not filtering that variable a bit of the point with JSONP?

+1  A: 

I think it is safe. As long as you do not echo $_GET['callback'] in another page without escaping. The one who does the request can put whatever js he wants in it, I think it will always be his problems, not yours. This page provides the definition of a valid js function name : http://www.functionx.com/javascript/Lesson05.htm

greg0ire
+1  A: 

No, if you intend to limit the JSONP to select domains. Specify the encoding too or people who shouldn't be able to access the JSON can possibly do UTF-7 injection attacks. Use this header instead:

header('Content-Type: application/json; charset=utf-8');

If it's supposed to be a public JSONP service, then yes it is safe.

Eli Grey
Ooh, never heard about that before. Think I'll def specify the encoding!
Svish
Except for a JSONP response you should use application/javascript rather than application/json seeing as JSONP is actually javascript code.
Julian Aubourg