Manx_Warrior
Manx_Warrior

Reputation: 99

Send JSON from one server and receive at another server

Hello I am passing an JSON array from one server say www.example1.com and I want to receive that data on another server say www.example2.com/test.php . I have tried this using cURL but I am not getting that data at the receiving. Following is my code

Code at Sender

$send_data = json_encode($myarray);            
$request_url  = 'www.example2.com/test.php';
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $request_url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, 'send_data='.$send_data);
$response = curl_exec($curl);
$curl_error = curl_error($curl);
curl_close($curl); 

Code at Receiver

if(isset($_REQUEST['send_data'])){
    $userinfo = json_decode($_REQUEST['send_data'],true);
    print_r($userinfo);
}

How do I fetch the data at receiver's end.

Upvotes: 0

Views: 2124

Answers (2)

Sinsil Mathew
Sinsil Mathew

Reputation: 498

Try this method.

FILE: example1.com/sender.php

$request_url  = 'www.example2.com/test.php';
$curl = curl_init( $request_url );
# Setup request to send json via POST.
$send_data = json_encode($myarray);  
curl_setopt( $curl, CURLOPT_POSTFIELDS, $send_data );
curl_setopt( $curl, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
# Return response instead of printing.
curl_setopt( $curl, CURLOPT_RETURNTRANSFER, true );
# Send request.
$result = curl_exec($curl);
curl_close($curl);
# Print response.
echo "<pre>$result</pre>";

on your second page, you can catch the incoming request using file_get_contents("example1.com/sender.php"), which will contain the POSTed json. To view the received data in a more readable format, try this:

echo '<pre>'.print_r(json_decode(file_get_contents("example1.com/sender.php")),1).'</pre>';

Upvotes: 1

v2solutions.com
v2solutions.com

Reputation: 1439

Use the following

FILE: example1.com/sender.php

<?php
header('Content-Type: application/json'); echo
json_encode(array('response1' => 'This is response1', 'response2' => 'This is response2', $_POST));
?>

FILE: example2.com/receiver.php

<?php
$request_url  = 'http://www.example1.com/sender.php';
$sendData = array('postVar1' => 'postVar1');
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $request_url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, 'sendData=' . http_build_query($sendData));

print_r($response = curl_exec($curl));

curl_close($curl);
?>

You will get a JSON object as a cURL response.

Upvotes: 0

Related Questions