Home > Net >  Curl didn't work PHP, always return empty esponse
Curl didn't work PHP, always return empty esponse

Time:11-30

I always get the return empty when I call my api with this code, but it work on my Insomnia, and on my shell

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_HTTPHEADER, $this->headers);
        curl_setopt($ch, CURLINFO_HEADER_OUT, true);
        curl_setopt($ch, CURLOPT_URL, $this->url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($this->body));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

        $return_data = curl_exec($ch);
        curl_close($ch);
        
        if ($return_data) return $return_data;
        else return "empty";

my curl_getinfo return :

[content_type] => text/html;charset=UTF-8
[http_code] => 500
[header_size] => 543
[request_size] => 164
[filetime] => -1
[ssl_verify_result] => 0
[redirect_count] => 0
[total_time] => 0.269685
[namelookup_time] => 0.002741
[connect_time] => 0.024587
[pretransfer_time] => 0.157608
[size_upload] => 636
[size_download] => 0
[speed_download] => 0
[speed_upload] => 2364
[download_content_length] => -1
[upload_content_length] => 636
[starttransfer_time] => 0.157693
[redirect_time] => 0 

CodePudding user response:

I fix my problem, thanks to insomnia who can generate PHP code for cURL,
I put the answer in case someone need it

    $curl = curl_init();

    curl_setopt_array($curl, [
        CURLOPT_URL => $this->url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => "",
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 30,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => "POST",
        CURLOPT_POSTFIELDS => json_encode($body),
        CURLOPT_HTTPHEADER => [
            "Accept: application/json",
            "Accept-Charset: UTF-8",
            "Content-Type: application/json"
        ],
    ]);

    $response = json_decode(curl_exec($curl));
  • Related