php curl自定义header疑难解惑

像下面一段php curl获取网页的代码

function curl_file_get_contents($durl, $data = null){
    $header = array();
    $header[] = "X-PJAX: 0";
    $header[]  =  "User-Agent: pjax";
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $durl);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true) ;
    //curl_setopt($ch, CURLOPT_BINARYTRANSFER, true) ;
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    
    if (!empty($data)) {
        curl_setopt($ch,CURLOPT_HTTPGET, 1);
        curl_setopt($ch,CURLOPT_POSTFIELDS,http_build_query($data));
    }
    if(!empty($header)){
        curl_setopt($ch,CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch,CURLOPT_HEADER, 0);//返回response头部信息
    }
    $res = curl_exec($ch);
    curl_close($ch);
    return $res;
}

其中自定义X-PJAX,

$header[] = "X-PJAX: 0";

在$_SERVER中的转义为HTTP_X_PJAX,

注意变化,前面会自动加上HTTP_,

并且你的-符号转化为_符号,使用时,请注意这两点,

否则你会摸不着头脑。正确姿势如下:

function is_pjax(){
  return array_key_exists('HTTP_X_PJAX', $_SERVER) && isset($_SERVER['HTTP_X_PJAX']);
}
if(is_pjax()){
echo "对的,就是它,就是无白屏加载我的";
}
点赞