Home > Blockchain >  Sending array using curl
Sending array using curl

Time:12-03

I want to send data from server 1 to server 2, first I select necessary data from the database, but how to send data with curl? I understand that I cannot send $result parameter just like in my code, but how should I do this?

My Code server 1:

public function setDivisions(){
        $result = $this->conn->query("SELECT *FROM data_divisions");
        $ch = curl_init('https://example.com/api.php?siteid='.$this->site_key.'');
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS,  $result);
        curl_setopt($ch, CURLOPT_POST, 1);
        $response = curl_exec($ch);
        print_r($response);
    }

Code on server 2:

 $array = $_POST['result'];
    //loop throw array and insert data into database

CodePudding user response:

you can use it that way.

$ch = curl_init('https://upxxx.cod3fus1ontm.com/curl/json');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode((object)["records" => json_encode($result)]));
$response = curl_exec($ch);
var_dump($response);

on receipt, like this!

$json = file_get_contents("php://input");
$content = json_decode($json, true);
$records = json_decode($content['records'], true);
foreach($records as $record) {
    echo $record['id'] . " - " . $record['text'] . "<br/>";
}

remember, that as you did to encode, you will have to do to decode

CodePudding user response:

Come on, php://input returns all raw data after the request's HTTP headers, regardless of content type. When we do this with file_get_contents (which reads the contents of a file and puts it into a variable of type string), we can read the content that was sent by curl. Reviewing the code, you can optimize as follows, when sending to the server you placed, I suggested:

curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode((object)["records" => json_encode($result)]));

you can replace it with:

curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($result));

it's much simpler, but it's very important to put the query result inside a json_encode

finally, you can access the entire body of the message, through file_get_contents ("php://input") and put it inside a variable, which is nothing more than a JSON of the your query. for you to understand how the parameters were passed, it is interesting to do the following:

$json = file_get_contents("php: // input");
var_dump($json); <- Here you see the thing as it is.
$records = json_decode($json, true); <- Here you generate an object with the content of json
var_dump($records);

With that, I think that solves the situation.

  • Related