简体   繁体   English

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);

Result 结果

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

But I want to get all Location at one time 但我希望一次获得所有Location

I enter > http://fb.com

then 301 redirect: http://www.facebook.com/?_rdr

then 302 redirect: https://www.facebook.com/

I want to get All this link at one time with status 301 302 我希望一次获得All this链接,状态为301 302

or any better idea to get redirect location url . 或任何更好的想法来获取重定向位置网址。 THANKS 谢谢

You can get all headers from every request made until no Location header is sent using this: 您可以从每个请求中获取所有标头,直到没有使用此方式发送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);

But then, you'll have to extract the information yourself because $headers is only a string, not an array. 但是,您必须自己提取信息,因为$headers只是一个字符串,而不是一个数组。

If you only need the last location, simply do curl_getinfo($ch,CURLINFO_EFFECTIVE_URL) . 如果您只需要最后一个位置,只需执行curl_getinfo($ch,CURLINFO_EFFECTIVE_URL)

Use curl_getinfo() to check if you got a 301 or 302 response and then repeat the same code again as long as that's the case. 使用curl_getinfo()检查是否有301或302响应,然后再次重复相同的代码,只要是这种情况。 So, put your code in a function like: 所以,将代码放在如下函数中:

$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);
}

Then $headers will hold all the headers encountered up until the first non-301/302 response. 然后$headers将保留所有遇到的标头,直到第一个非301/302响应。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM