ArrayString

ArrayString

Who am I?


What I write about


Recent Posts

php中获取curl请求的请求头信息及相应头信息

获取请求头信息,可以在curl_exec函数执行前,添加代码

 curl_setopt($ch,CURLINFO_HEADER_OUT,true);

在curl_exec函数执行后,通过

 curl_getinfo($ch,CURLINFO_HEADER_OUT);

来获取curl执行请求的请求数据。

获取响应头信息,可以在curl_exec函数执行前,添加代码

curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_NOBODY,true); 

之后 通过curl_exec函数来获取响应头信息。获取设置

curl_setopt($ch, CURLOPT_NOBODY,false);

然后对curl_exec获取的值通过\r\n\r\n进行分割截取第一部分即为响应头信息。

function curlRequest($url='', $postFields='' ,$header=['Content-Type: application/json; charset=utf-8'])
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
    curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
    curl_setopt($ch, CURLOPT_TIMEOUT, 60);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);

    // curl_setopt($ch, CURLOPT_HEADER, true);        //返回头信息
    // curl_setopt($ch, CURLOPT_NOBODY, true);        //不返回内容

    curl_setopt($ch,CURLINFO_HEADER_OUT,true);

    $ret = curl_exec($ch);
    $out = curl_getinfo($ch,CURLINFO_HEADER_OUT);
    var_dump($out,$postFields);
    if (!$ret)
    {
        $result = curl_error($ch);
    }
    else
    {
        $rsp = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        if ($rsp != 200)
        {
            $result = "请求状态 " . $rsp . " " . curl_error($ch);
        }
        else
        {
            $result = $ret;
        }
    }
    curl_close($ch);
    return $result;
}