rgunning
rgunning

Reputation: 568

php file_get_contents("php://input") adding quotes

I'm having issues using POST with a php REST server. file_get_contents("php://input") is adding additional quotes. This is causing json_decode(file_get_contents("php://input"),true) to fail

i.e. I am posting stringified JSON

'{"someValue":0,"someOtherValue":1}'

PHP:

var_dump(file_get_contents("php://input"))

returns

string(173) "'{  "someValue" : 0,   "someOtherValue" : "1"}'"

My PHP version is 5.3.10

To post the json, I am currently using the webstorm REST Client tool

Headers: 
    Accept: */*
Request Body:
    Text: '{  "someValue" : 0,   "someOtherValue" : "1"}'

I tried removing the outer quotes from the string in webstorm and it would work I.E. { "someValue" : 0, "someOtherValue" : "1"}

I moved to debugging in webstorm after initially hitting the bug in an angular application using angular ngResource

Controller

angular
    .module('app.bookings')
    .controller('BookAPuntController', BookAPuntController);
BookAPuntController.$inject(BookingServices);
function BookAPuntController(BookingServices) {
    var data = {
      someValue:0,
      someOtherValue:1
    };
    BookingServices.save(JSON.stringify(data));
};

booking.dataservice.js

(function () {
  'use strict';

  angular
    .module('app.data')
    .factory('BookingServices', BookingServices);

  BookingServices.$inject = ['$resource'];

  /* @ngInject */
  function BookingServices($resource) {
    return $resource('rest/booking/:Id/:from/:to', null, {
      'get': {method: 'GET', isArray: true},
    });
  }

})();

Upvotes: 1

Views: 1135

Answers (2)

rgunning
rgunning

Reputation: 568

Turns out I was asking the entirely wrong question

My angular application was failing with it's POST due to CORS. I was running the App on localhost but querying the remote REST php server. When I ran the application a method OPTIONS request was being sent due to CORS. The server didn't know how to respond so everything failed.

debugging in webstorm was artificially introducing the error seen in the original question.

Why am I getting an OPTIONS request instead of a GET request?

https://serverfault.com/questions/231766/returning-200-ok-in-apache-on-http-options-requests

Upvotes: 0

Poiz
Poiz

Reputation: 7617

'{"someValue":0,"someOtherValue":1}'; // IS A STRING...
 {"someValue":0,"someOtherValue":1};  // IS NOT A STRING...

If you are passing-in the first variant; You should get back a String like PHP smartly figured out and returned...

string(173) "'{  "someValue" : 0,   "someOtherValue" : "1"}'"

When you pass in the result of

var jsonData = JSON.stringify(data);

You may have solved your Problem, Yourself....

Upvotes: 3

Related Questions