php curl有时候我们需要设置header和获取header、网页返回码。
如下方法可以拿到
public function getCurlHttpHeader($url, $headers = null) { if (empty($headers)) { $headers = []; } $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); //是否抓取跳转后的页面 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查 curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, true); // 从证书中检查SSL加密算法是否存在 curl_setopt($ch, CURLOPT_TIMEOUT, 10); // 设置超时限制防止死循环 curl_setopt($ch, CURLOPT_HEADER, 1); //取得返回头信息 $res = curl_exec($ch); $headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE); $header = substr($res, 0, $headerSize); $body = substr($res, $headerSize); curl_close($ch); return ['body' => $body, 'head' => $header]; }
或者使用curl_getinfo($ch, CURLINFO_HTTP_CODE) 来判断返回码
关键字词: