【问题标题】:Get data that PHP curl is sending获取 PHP curl 正在发送的数据
【发布时间】:2016-04-29 01:05:07
【问题描述】:

PHP 的 curl 令人惊讶地无法调试且晦涩难懂。我在使用 cURL 下载 JSON API 数据时遇到问题。我想看看 cURL 到底是什么发送到远程 HTTP 服务器。

目前我唯一的调试选项是临时将请求发送到一些将输入写入标准输出的简单 HTTP 服务器。我需要编写该服务器来调试 curl!

我做什么:

function get_data($url) {
  $ch = curl_init();
  echo "Download: $url.\n";
  curl_setopt($ch, CURLOPT_URL, $url);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
  curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
  curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
  // I hoped to get some debug info
  // but this setting has no effect
  curl_setopt($ch, CURLOPT_VERBOSE, true);    
  curl_setopt($ch, CURLOPT_HEADER, array(
    'User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:43.0) Gecko/20100101 Firefox/43.0',
    'X-Purpose: Counting downloads.'
  ));

  echo "Sending: \n".curl_getinfo($ch, CURLINFO_HEADER_OUT);
  $data = curl_exec($ch);

  var_dump($data);
  echo curl_error($ch)." ".curl_errno($ch);
  curl_close($ch);
  return $data;
}

如何获取 cURL 作为文本发送的数据?

【问题讨论】:

    标签: php curl


    【解决方案1】:

    如果你想定义标题你应该使用CURLOPT_HTTPHEADERnot CURLOPT_HEADER,即:

      curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        'User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:43.0) Gecko/20100101 Firefox/43.0',
        'X-Purpose: Counting downloads.'
      ));
    

    要获取 curl 发送的内容,请使用:

    curl_setopt($handle, CURLOPT_VERBOSE, true);
    curl_setopt($handle, CURLOPT_STDERR,$f = fopen($verbosePath, "w+"));
    

    function get_data($url) {
    $verbosePath = __DIR__.DIRECTORY_SEPARATOR.'verbose.txt';
    echo "Saving verbose to: $verbosePath\n";
    $handle=curl_init('http://www.google.com/');
    curl_setopt($handle, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($handle, CURLOPT_CONNECTTIMEOUT, 5);
    curl_setopt($handle, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($handle, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($handle, CURLOPT_HTTPHEADER, array(
        'User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:43.0) Gecko/20100101 Firefox/43.0',
        'X-Purpose: Counting downloads.'
      ));
    curl_setopt($handle, CURLOPT_VERBOSE, true);
    curl_setopt($handle, CURLOPT_STDERR,$f = fopen($verbosePath, "w+"));
    $data = curl_exec($handle);
    curl_close($handle);
    fclose($f);
    return $data;
    }
    
    get_data("https://www.google.com");
    

    verbose.txt

    * About to connect() to www.google.com port 80
    *   Trying 172.217.0.100... * connected
    * Connected to www.google.com (172.217.0.100) port 80
    > GET / HTTP/1.1
    Host: www.google.com
    Accept: */*
    User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:43.0) Gecko/20100101 Firefox/43.0
    X-Purpose: Counting downloads.
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-08
      • 1970-01-01
      • 2016-06-14
      • 2021-04-30
      • 2018-12-21
      相关资源
      最近更新 更多