I have a file called action.php that will do some action. I want to expose this as either a plain JSON or JSONP output. The user will call this using a URL like this:
action.php?jsonp=callback
In my action.php I am doing something like this
$jsonp = isset $_GET["jsonp"] ? $_GET["jsonp"] : false;
$output = execute_action();
if ($jsonp) {
header('Content-Type: application/javascript');
printf("%s(%s)", $jsonp, json_encode($output));
} else {
header('Content-Type: application/json');
echo json_encode($output);
}
But this seems unsafe to me. Should I validate or escape the jsonp callback parameter if it is passed in? If so, what situation would this protect against, and how should I do it in PHP?
Let's assume that this action.php is exposed to the internet as a service for any website to use (including my own).
Edit: For clarity my question has 2 parts:
Your opinion on the importance of protecting a hypothetical 3rd party site from harmful jsonp injections
Now supposing I wanted to protect 3rd party sites using my service, should I validate the jsonp parameter (i.e. maybe only allow certain characters?), or should I escape the jsonp output (if so what
php
function should I use?)
For me to mark the answer as accepted, I would like some more input on both of these questions.