How to send a json via post with PHP?

-1

Good people,

I need to send a json via post to an API (URL: link ) and read what to return? How can I do it? I thought of something with cURL.

Thankful

    
asked by anonymous 01.04.2017 / 02:41

2 answers

4

First you should instantiate an array with the fields you want to send:

$array = array("cor" => "vermelho", "ano" => "2012");

Then you have to use the json_encode function to generate the JSON:

$json = json_encode($array);

The CURL function call should look like this:

$ch = curl_init('URL_DA_CHAMADA');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($json))
);

Callback handling should happen on the variable that is receiving the curl_exec result, if the return is a JSON too, you should use the json_decode function.

$jsonRet = json_decode(curl_exec($ch));

    
01.04.2017 / 15:22
1

The page is protected for logged-in users, so you may need to send session cookies ( the session name is ASP.NET_SessionId ), a simplistic way is to use:

$cabeçalho = ['Cookie: ASP.NET_SessionId=' . $ValorSessao];

In addition, as a bitcoin exchange website should require you to use a valid UA, so also use a valid User-Agent.

Set the POST method:

CURLOPT_POST => true

Also define what you are going to send:

CURLOPT_POSTFIELDS => $ConteudoQueQuerEnviar

Logo:

$ConteudoPOST = json_encode($sua_array);
$ConteudoCabecalho = [
    'Cookie: ASP.NET_SessionId=XXXXXXXXXXXXXXXXXXX;',
    'User-Agent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36'
]

Defined this use CURL:

$curl = curl_init('https://www.bitcointoyou.com/Payments/');

curl_setopt_array($curl, [

    //-------- Segurança (caso se preocupe com isto):
    // Verifica o SSL (dificultar MITM):        
    CURLOPT_SSL_VERIFYHOST => 1,
    CURLOPT_SSL_VERIFYPEER => 2,

    // Limita o CURL para o protocolo HTTPS (dificultar SSRF e "downgrade"):
    CURLOPT_PROTOCOLS => CURLPROTO_HTTPS,

    // Limita para não seguir redirecionamento (mesmo motivo acima):
    CURLOPT_FOLLOWLOCATION => 0,
    CURLOPT_MAXREDIRS => 0,

    // Define um Tempo limita (dificultar DoS por Slow HTTP):
    CURLOPT_CONNECTTIMEOUT => 1,
    CURLOPT_TIMEOUT => 3,
    CURLOPT_LOW_SPEED_LIMIT => 750,
    CURLOPT_LOW_SPEED_TIME => 1,        
    //--------

    // Define como método POST:
    CURLOPT_POST => 1,

    // Define o JSON (o corpo do POST):
    CURLOPT_POSTFIELDS => $ConteudoPOST,

    // Define o cabeçalho:
    CURLOPT_HTTPHEADER => $ConteudoCabecalho,

    // Define para retornar o conteúdo para a variável:
    CURLOPT_RETURNTRANSFER => 1
]);

$RespostaCURL = curl_exec($curl);
    
01.04.2017 / 16:07