PHP - 发送 HTTP 请求并记录完整的响应(标头 + 有效负载)


PHP - send HTTP Request and log the full response (headers + payload)

我使用此函数发出我的HTTP请求,并成功获取了响应的正文:

function SendRequest($url, $method, $data, $headers){
    $context = stream_context_create(array
    (
        'http' => array(
            'method' => $method,
            'header' => $headers,
            'content' => $data
        )
    ));
    return file_get_contents($url, false, $context);
}

但是我需要一种方法来获取整个HTTP响应(包括标头)!无论是出于调试还是出于实际原因。

例如,假设我请求登录网络服务,并且在响应中有一个会话cookie。这样我就无法得到它。

*如果可能的话,如果有一种方法可以记录去虫请求,那就太好了。

查看 stream_get_meta_data() 函数。 对于 http 流,它将在 wrapper_data 2 中包含 HTTP 响应标头和状态行

我找到了一种通过使用$http_response_header的方法。

function SendRequest($url, $method, $data, $headers) {
    $context = stream_context_create(array
    (
        'http' => array(
            'method' => $method,
            'header' => $headers,
            //'content' => http_build_query($data)
            'content' => $data
        )
    ));
    $response_body = file_get_contents($url, false, $context);
    //var_dump($http_response_header);
    return array(
        'headers' => $http_response_header, 
        'body' => $response_body
    ); 
}

*$http_响应_标头将在本地范围内创建