PHP curl () gets the whole header in one go

<?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 everything Locationin one go

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 in one go with status 301 302

or any better idea to get a redirect url. THANKS

+4
source share
2 answers

You can get all the headers from each request until the header is sent Locationusing this:

$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 will need to extract the information yourself, because $headers- this is only a string, not an array.

If you only need the last place, just do it curl_getinfo($ch,CURLINFO_EFFECTIVE_URL).

+4
source

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.

+1

All Articles