I
I
Igor Vorotnev2014-05-31 15:19:22
PHP
Igor Vorotnev, 2014-05-31 15:19:22

json exchange between PHP scripts on different servers

Greetings!
Task: On one server there is a folder with .txt files, they contain pure JSON. I read data from these files with the client.php script located next to the folder, now I need to send the read data to another server. The server.php script is located on the remote server, which should receive this data, give a response to the client.php script, process it and save it to a .txt file in JSON format.
I read files from client.php without problems. From server.php to write to a file - also ok. The problem is in the middle. I can’t send data in any way, apparently, they don’t even reach server.php. What am I doing wrong?
client.php:

<?php
$api_key = 'B12347162936387BB33534B85C873'; // Для простой проверки
$api_url = 'http://remote.dev/server.php'; // Куда отправлять
$file = '20140525/data.txt'; // Локальный файл с json-данными
$json_data = file_get_contents( $file ); // Читаем из файла
// Пробуем отправить, для начала только $api_key
$curl = curl_init($api_url);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HEADER, 0);
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($api_key));
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
                                            'Content-Type:application/json',
                                            'Content-Length:'.strlen($api_key)
                                        ));
$json_response = curl_exec($curl);
$curl_errorno = curl_errno($curl);
$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
echo $json_response; // Выводим ответ
curl_close($curl);
?>

server.php:
<?php
$api_key = 'B12347162936387BB33534B85C873'; // Для сверки
print_r ($_POST); // Смотрим прилетели ли данные?
print_r ($_REQUEST); // Может сюда прилетели?
?>

Received response - 2 empty arrays:
Array ( ) Array ( )
What's wrong? I've been banging my head against the wall for an hour now. Google did not help, documentation on curl_setopt () too. I tried to send different variations - $api_key, $data, collected them into one array, translated them into json, and so on. The answer is the same, empty arrays.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
Ruslan, 2014-05-31
@HeadOnFire

It is necessary to pass an array or receive raw data - $HTTP_RAW_POST_DATAorphp://input

C
cmx, 2014-05-31
@cmx

I think the problem is that you do not explicitly specify in which field to transfer data. Try the following construction:

curl_setopt($curl, CURLOPT_POSTFIELDS, array(
    'apikey' => $api_key,
    'data' => $json_data,
));

You can also try specifying the entire file to transfer at once.
Original: www.php.net/manual/en/function.curl-setopt.php

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question