分类 php 下的文章

有时候接口问题比较难调, 需要整个完整请求链路过程的记录. 有了请求报文和响应报文,就很好的定位问题. curl是支持打印出这些信息的, 很简单,一行配置搞定. 话不多说,直接上代码(将如下配置放在curl_exec前即可了)

$f = fopen('curl_debug', 'wb');
curl_setopt($ch,CURLOPT_VERBOSE,true);//默认是标准错误输出中
curl_setopt($ch,CURLOPT_STDERR ,$f);//有了该指令,请求过程记录会写到该文件中

文件中内容,大概是如下(本身输出内容是不包含响应body的,有需要你可自己追加在该文件后,便更好查看)

*   Trying 14.215.177.39...
* TCP_NODELAY set
* Connected to www.baidu.com (14.215.177.39) port 80 (#0)
> GET / HTTP/1.1
Host: www.baidu.com
Accept: */*

< HTTP/1.1 200 OK
< Accept-Ranges: bytes
< Cache-Control: no-cache
< Connection: keep-alive
< Content-Length: 14615
< Content-Type: text/html
< Date: Tue, 02 Nov 2021 16:34:39 GMT
< Pragma: no-cache
< Server: BWS/1.1
< Vary: Accept-Encoding
< 
* Connection #0 to host www.baidu.com left intact

ps: 有点需要注意, curl本身的bug,导致如果CURLINFO_HEADER_OUT设置为true时(即开启输出响应头), CURLOPT_VERBOSE会不生效.所以你需要将CURLINFO_HEADER_OUT配置去掉.

用这种方法不仅优雅,而且是最准确.像自己根据响应的换行去分隔会有不准确的情况发生.

$headers = [];
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

// this function is called by curl for each header received
curl_setopt($ch, CURLOPT_HEADERFUNCTION,
  function($curl, $header) use (&$headers)
  {
    $len = strlen($header);
    $header = explode(':', $header, 2);
    if (count($header) < 2) // ignore invalid headers
      return $len;

    $headers[strtolower(trim($header[0]))][] = trim($header[1]);

    return $len;
  }
);

$data = curl_exec($ch);
print_r($headers);