Make WordPress Core

Changeset 39609


Ignore:
Timestamp:
12/16/2016 05:42:23 AM (10 years ago)
Author:
dd32
Message:

REST API: Do not error on empty JSON body

It's fairly common for clients to send Content-Type: application/json with an
empty body. While technically not valid JSON, we've historically supported
this behaviour, so it shouldn't cause an error.

Props JPry, jnylen0.
Merges [39594] to the 4.7 branch.
Fixes #39150.

Location:
branches/4.7
Files:
3 edited

Legend:

Unmodified
Added
Removed
  • branches/4.7

  • branches/4.7/src/wp-includes/rest-api/class-wp-rest-request.php

    r39111 r39609  
    670670                }
    671671
    672                 $params = json_decode( $this->get_body(), true );
     672                $body = $this->get_body();
     673                if ( empty( $body ) ) {
     674                        return true;
     675                }
     676
     677                $params = json_decode( $body, true );
    673678
    674679                /*
  • branches/4.7/tests/phpunit/tests/rest-api/rest-request.php

    r39109 r39609  
    1111 */
    1212class Tests_REST_Request extends WP_UnitTestCase {
     13        public $request;
     14
    1315        public function setUp() {
    1416                parent::setUp();
    … …  
    413415                $data = $valid->get_error_data();
    414416                $this->assertEquals( JSON_ERROR_SYNTAX, $data['json_error_code'] );
     417        }
     418
     419
     420        public function test_has_valid_params_empty_json_no_error() {
     421                if ( version_compare( PHP_VERSION, '5.3', '<' ) ) {
     422                        return $this->markTestSkipped( 'JSON validation is only available for PHP 5.3+' );
     423                }
     424
     425                $this->request->set_header( 'Content-Type', 'application/json' );
     426                $this->request->set_body( '' );
     427
     428                $valid = $this->request->has_valid_params();
     429                $this->assertNotWPError( $valid );
    415430        }
    416431
Note: See TracChangeset for help on using the changeset viewer.