PHP curl() 一次获取所有标头


PHP curl() get all header at one time

<?php
    $url = 'http://fb.com';
    $curl = curl_init();
    curl_setopt_array($curl, array(
        CURLOPT_URL => $url,
        CURLOPT_HEADER => true,
    ));
    $header = explode("'n", curl_exec($curl));
    curl_close($curl);
    print_r($header);

结果

HTTP/1.1 301 Moved Permanently
Location: http://www.facebook.com/?_rdr
Vary: Accept-Encoding
Content-Type: text/html
X-FB-Debug: rVg0o+qDt9z/zJu7jTW1gi1WSRC8YIMu3e6XnPagx39zZ4pbV0k2yrNfZmkdTLZyfzg713X+M0Lr2jS2P018xA==
Date: Thu, 25 Feb 2016 08:48:08 GMT
Connection: keep-alive
Content-Length: 0

但我想一次得到所有Location

I enter > http://fb.com
then 301 redirect: http://www.facebook.com/?_rdr
then 302 redirect: https://www.facebook.com/

我想一次获取所有这些链接,状态301 302

或任何更好的主意来获取重定向位置网址。谢谢

您可以使用以下命令从发出的每个请求中获取所有标头,直到没有发送Location标头:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_NOBODY, true);
$headers = curl_exec($ch);
curl_close($ch);

但是,您必须自己提取信息,因为$headers只是一个字符串,而不是数组。

如果您只需要最后一个位置,只需执行curl_getinfo($ch,CURLINFO_EFFECTIVE_URL)

使用 curl_getinfo() 检查您是否收到 301 或 302 响应,然后再次重复相同的代码,只要是这种情况。因此,将您的代码放入如下函数中:

$headers = array();
function getHeaders($url) {
    $curl = curl_init();
    curl_setopt_array($curl, array(
        CURLOPT_URL => $url,
        CURLOPT_HEADER => true,
    ));
    $header = explode("'n", curl_exec($curl));
    if (in_array(curl_getinfo($curl, CURLINFO_HTTP_CODE), array(301, 302))) {
        // Got a 301 or 302, store this stuff and do it again
        $headers[] = $header;
        curl_close($curl);
        return getHeaders($url);
    }
    $headers[] = $header;
    curl_close($curl);
}

然后$headers将保留遇到的所有标头,直到第一个非 301/302 响应。