Browse Source

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 '{'
Aalhad Saraf 7 years ago
parent
commit
b7467941a1
2 changed files with 11 additions and 0 deletions
  1. 1
    0
      api.php
  2. 10
    0
      tests/Tests.php

+ 1
- 0
api.php View File

@@ -1679,6 +1679,7 @@ class PHP_CRUD_API {
1679 1679
 	}
1680 1680
 
1681 1681
 	protected function retrieveInputs($data) {
1682
+		$data = trim($data, " \t\n\r");
1682 1683
 		if (strlen($data)==0) {
1683 1684
 			$input = false;
1684 1685
 		} else if ($data[0]=='{' || $data[0]=='[') {

+ 10
- 0
tests/Tests.php View File

@@ -643,4 +643,14 @@ abstract class Tests extends TestBase
643 643
         $test->get('/posts/1');
644 644
         $test->expect('{"id":1,"user_id":1,"category_id":1,"content":"blog start\'d"}');
645 645
     }
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
+    }
646 656
 }

Loading…
Cancel
Save