0

I am develop a php data interface. But I can't get the data.

A.php

$options = [
       'http' => [
            'method'  => 'POST',
            'content' => $data,
            'header'  => "Content-Type: application/json\r\n" .
                         "Accept: application/json\r\n"
        ]
    ];
    $context  = stream_context_create( $options );
    $result   = file_get_contents('B.php', false, $context );
    echo $result; //Output: I have recvieve it. // It's proves that the url is right.

B.php

$data = $_POST; // The $data is empty. Why??? It can't get the data
echo 'I have recvieve it';
YakovL
  • 7,557
  • 12
  • 62
  • 102
Tom Tao
  • 97
  • 7
  • 2
    What is `$data` in A? – Jonnix Jan 26 '18 at 11:38
  • You're also doing `print_r($data)` or something to prove the data is empty…? – deceze Jan 26 '18 at 11:39
  • 4
    That's why: `Content-Type: application/json` http://php.net/manual/en/reserved.variables.post.php: _"An associative array of variables passed to the current script via the HTTP POST method **when using application/x-www-form-urlencoded or multipart/form-data as the HTTP Content-Type** in the request."_ – CBroe Jan 26 '18 at 11:40
  • If you really want to POST a **JSON** body, you have to use another API, e.g. **[curl](https://stackoverflow.com/questions/16920291/post-request-with-json-body)**. – rustyx Jan 26 '18 at 11:48
  • I think i has found the reason. There are not only one way to get API data. Base the answer by CBroe. I use the $data = file_get_contents('php://input', 'r'); – Tom Tao Jan 26 '18 at 12:26

0 Answers0