What Steps do you Take to Troubleshoot Problems with PHP cURL?

后端 未结 2 1575
误落风尘
误落风尘 2021-02-02 00:11

Almost any working PHP programmer has faced having to use CURL to send raw HTTP requests, whether it\'s for credit card payment processing, nefarious screen scraping, or somethi

相关标签:
2条回答
  • 2021-02-02 00:42

    I find the CURLINFO_HEADER_OUT option to be very useful.

    <?php
    $curl = curl_init('http://www.php.net');
    
    curl_setopt($curl, CURLOPT_HEADERFUNCTION, 'dbg_curl_data');
    curl_setopt($curl, CURLOPT_WRITEFUNCTION, 'dbg_curl_data');
    curl_setopt($curl, CURLINFO_HEADER_OUT, true);
    
    curl_exec($curl);
    
    echo '<fieldset><legend>request headers</legend>
      <pre>', htmlspecialchars(curl_getinfo($curl, CURLINFO_HEADER_OUT)), '</pre>
    </fieldset>';
    
    echo '<fieldset><legend>response</legend>
      <pre>', htmlspecialchars(dbg_curl_data(null)), '</pre>
    </fieldset>';
    
    function dbg_curl_data($curl, $data=null) {
      static $buffer = '';
    
      if ( is_null($curl) ) {
        $r = $buffer;
        $buffer = '';
        return $r;
      }
      else {
        $buffer .= $data;
        return strlen($data);
      }
    }
    0 讨论(0)
  • 2021-02-02 01:05

    Actually, I never use CURL (in php). The PHP stream api is much neater, and can be used to POST data as well. Wez Furlong has an article about this.

    If I were to use it? I'd start with turning on all messages (setting error reporting to E_ALL). If I find that PHP doesn't tell me what I need in the error messages, I'd probably use a proxy approach to see what's actually going on. Changing the target url to a local php page containing something like

    <?php
    var_dump($_POST);
    var_dump($_GET);
    var_dump($_SERVER);
    

    is one way. Another way is to use a utility like netcat to listen on port 80 and send the request there:

    netcat -l -p 80
    

    This won't return anything to curl, but it will allow you to see exactly what is sent the server, which might be enough to diagnose the problem.

    You can also retrieve the headers from PHP using the apache_request_headers() function. In most cases I prefer the netcat approach, though, since it guarantees that I see the unmodified truth, and also display the raw post data.

    0 讨论(0)
提交回复
热议问题