Skip to content

Commit 7e262f4

Browse files
committed
Added automated jsonp support with validation based on the presence of
the 'callback' GET param; Also works should: * the requesting Content-Type is application/json instead of application/javascript; * the format GET param is: json * file extension: .json
1 parent 7c1848d commit 7e262f4

File tree

1 file changed

+26
-1
lines changed

1 file changed

+26
-1
lines changed

application/libraries/Format.php

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -210,7 +210,32 @@ public function to_csv()
210210
// Encode as JSON
211211
public function to_json()
212212
{
213-
return json_encode($this->_data);
213+
$_numeric = strnatcmp(PHP_VERSION, '5.3.3') >= 0;
214+
$callback = isset($_GET['callback']) ? $_GET['callback'] : '';
215+
216+
// we only honour jsonp callback which are valid javascript identifiers
217+
if ($callback === '')
218+
{
219+
return $_numeric
220+
? json_encode($this->_data, JSON_NUMERIC_CHECK);
221+
: json_encode($this->_data);
222+
}
223+
else if (preg_match('/^[a-z_\$][a-z0-9\$_]*(\.[a-z_\$][a-z0-9\$_]*)*$/i', $callback))
224+
{
225+
// this is a jsonp request, the content-type must be updated to be text/javascript
226+
header("Content-Type: application/javascript");
227+
return $_numeric
228+
? $callback . "(" . json_encode($this->_data, JSON_NUMERIC_CHECK) . ");";
229+
: $callback . "(" . json_encode($this->_data) . ");";
230+
}
231+
else
232+
{
233+
// we have an invalid jsonp callback identifier, we'll return plain json with a warning field
234+
$this->_data['warning'] = "invalid jsonp callback provided: ".$callback;
235+
return $_numeric
236+
? json_encode($this->_data, JSON_NUMERIC_CHECK);
237+
: json_encode($this->_data);
238+
}
214239
}
215240

216241
// Encode as Serialized array

0 commit comments

Comments
 (0)