D
D
Damir Rysaev2014-12-03 23:08:07
PHP
Damir Rysaev, 2014-12-03 23:08:07

How to read JSON sent via curl to php://input?

I send data from one site:

// Содержимое запроса
  $body = json_encode(array ( 'data' => 'lorem', 'count' => 'infinity');

  // Создание временного файла, содержимое которого будет передано методом PUT
  $fp = fopen('php://temp/maxmemory:256000', 'w');
  fwrite($fp, $body);
  fseek($fp, 0);

  // Выполнение PUT-запроса и вывод результата
  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL, $url);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type: application/json', 'Accept: application/json', 'Expect:'));
  curl_setopt($ch, CURLOPT_PUT, true);
  curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
  curl_setopt($ch, CURLOPT_INFILE, $fp);
  curl_setopt($ch, CURLOPT_INFILESIZE, strlen($body));  

  $output = curl_exec($ch);		

  echo $output;

On the other I accept:
$str  = file_get_contents("php://input");
echo $str; // {"data" : "lorem", "count" : "infinity"}
$json = json_decode($str);
var_dump($json); // ничего не выводит

I can only output file_get_contents("php://input"), but I can't send the data in email or json_decode().

Answer the question

In order to leave comments, you need to log in

1 answer(s)
W
WebSpider, 2014-12-04
@WebSpider

echo $str; // ['data' : 'lorem', 'count' : 'infinity']

This is not valid JSON, or rather not JSON at all. JSON should look like this:
echo $str; // {'data' : 'lorem', 'count' : 'infinity'}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question