Skip to content

Commit b746794

Browse files
committed
Handle leading whitespace in JSON body
Issue: When sending JSON in the body of a POST request from an HTML form - for creating a new record, a new record was being created, but with null as the value for all the fields, instead of the values supplied. Cause: The template text in the textarea field, in the HTML form had some leading whitespace. On looking through the source, json_decode is being called only if the first character of the $data variable is a '{' or a '['. JSON Specification RFC4627 https://tools.ietf.org/html/rfc4627#section-2 says that insignificant whitespace is allowed before or after any of the six structural characters - '{','[',']','}',':',',' where whitespace is defined as: ws = *( %x20 / ; Space %x09 / ; Horizontal tab %x0A / ; Line feed or New line %x0D ; Carriage return ) Fix: trim the above characters from the beginning and ending of the received data before checking that the first character is a '[' or '{'
1 parent 9bbc5bb commit b746794

File tree

2 files changed

+11
-0
lines changed

2 files changed

+11
-0
lines changed

api.php

+1
Original file line numberDiff line numberDiff line change
@@ -1679,6 +1679,7 @@ protected function findRelations($tables,$database,$auto_include) {
16791679
}
16801680

16811681
protected function retrieveInputs($data) {
1682+
$data = trim($data, " \t\n\r");
16821683
if (strlen($data)==0) {
16831684
$input = false;
16841685
} else if ($data[0]=='{' || $data[0]=='[') {

tests/Tests.php

+10
Original file line numberDiff line numberDiff line change
@@ -643,4 +643,14 @@ public function testEditPostWithApostrophe()
643643
$test->get('/posts/1');
644644
$test->expect('{"id":1,"user_id":1,"category_id":1,"content":"blog start\'d"}');
645645
}
646+
647+
public function testAddPostWithLeadingWhitespaceInJSON()
648+
{
649+
$test = new Api($this);
650+
$test->post('/posts', '
651+
{"user_id":1,"category_id":1,"content":"test whitespace"} ');
652+
$test->expect('21');
653+
$test->get('/posts/21');
654+
$test->expect('{"id":21,"user_id":1,"category_id":1,"content":"test whitespace"}');
655+
}
646656
}

0 commit comments

Comments
 (0)