phpjson

Making POST application/json request with file_get_contents


I made a code in PHP. The code works correctly when I run the command:

$payload = file_get_contents ('request.json');

However, I need to create dynamic content for the parameters passed by request.json

I made a routine that generates a string with exactly the same content as in the request.json file. However, when I pass this content to the $payload my function does not work.

$options = array (
  'http' => array (
    'header' => "Content-type: application / json",
    'method' => 'POST',
    'content' => $reqjson,
  )
);

$context = stream_context_create ($options);
$result = file_get_contents ($url, false, $context);

Why is that? Isn't the type returned by the "file_get_contents" function a common string? How to fix it?


Solution

  • First, each line of header must end with "\r\n". Please append that to the "Content-Type" line. Second, if the function file_get_contents() returns false, it mean the request somehow failed. You should examine $http_response_header for more information:

    $options = array(
      'http' => array(
        'header' => "Content-type: application/json\r\n",
        'method' => 'POST',
        'content' => $reqjson,
      ),
    );
    
    $context = stream_context_create($options);
    if (($result = file_get_contents($url, false, $context)) === false) {
      var_dump($http_response_header);
    }
    

    If the response header ($http_response_header) starts with HTTP/1.0 400 Bad Request, it means that the server somehow think your request is malformatted. Then,

    1. If you have access to the requested server, try to find relevant log file(s) for more information.
    2. If you have documentations to the requested server / service, please check carefully the accepted request format.
    3. Often request format errors can be:
      • "appliation/json" is not an accepted request format; or
      • The content of $reqjson is malformat (e.g. it is supposed to be JSON text, not PHP array).
    4. If you're using 3rd party service and still cannot figure out why it doesn't give you the expected result, seek help from the service provider.