Make cURL output STDERR to file (or string)

后端 未结 6 1953
醉话见心
醉话见心 2020-12-03 11:30

We\'re trying to debug some cURL errors on the server, and I would like to see the STDERR log. Currently, all we can see for our error is \"error code: 7\" and that we can\'

6条回答
  •  误落风尘
    2020-12-03 12:08

    Putting al above answers together, I use this function to make a Curl Post Request with loggin to a file option:

    function CURLPostRequest($url, array $post = NULL, array $options = array(), $log_file = NULL){
        $defaults = array(
                CURLOPT_POST => 1,
                CURLOPT_HEADER => 0,
                CURLOPT_URL => $url,
                CURLOPT_FRESH_CONNECT => 1,
                CURLOPT_RETURNTRANSFER => 1,
                CURLOPT_FORBID_REUSE => 1,
                CURLOPT_TIMEOUT => 4,
                CURLOPT_POSTFIELDS => http_build_query($post)
        );
    
        if (is_resource($log_file)){
            $defaults[CURLOPT_VERBOSE]=1;
            $defaults[CURLOPT_STDERR]=$log_file;
            $defaults[CURLINFO_HEADER_OUT]=1;
        }
    
        $ch = curl_init();
        curl_setopt_array($ch, ($options + $defaults));
        if( ! $result = curl_exec($ch)){
            throw new Exception(curl_error($ch));
        }
    
        if (is_resource($log_file)){
    
            $info = curl_getinfo($ch);
    
            if (isset($info['request_header'])){
                fwrite($log_file, PHP_EOL.PHP_EOL.'* POST Content'.PHP_EOL.PHP_EOL);
                fwrite($log_file, print_r($info['request_header'],true));
                fwrite($log_file, http_build_query($post));
            }
    
            fwrite($log_file, PHP_EOL.PHP_EOL.'* Response Content'.PHP_EOL.PHP_EOL);
            fwrite($log_file, $result.PHP_EOL.PHP_EOL);
        }
    
        curl_close($ch);
        return $result;
    }
    

    Hope this help to someone.

提交回复
热议问题