Question

J'utilise une boucle pour faire php envoyer une requête http à un certain site Web quelque part et ont mis CURLOPT_FOLLOWLOCATION à 1 pour qu'il suive réoriente. Comment alors, puis-je savoir où il a finalement été redirigé?

Était-ce utile?

La solution

Vous pouvez faire quelque chose comme:

curl_getinfo($ch, CURLINFO_EFFECTIVE_URL); // returns the last effective URL

Autres conseils

$ch = curl_init( "http://websitethatredirects.com" );
$curlParams = array(
   CURLOPT_FOLLOWLOCATION => true,
);
curl_setopt_array( $ch, $curlParams );
$ret = curl_exec( $ch );
$info = curl_getinfo( $ch );
print $info['url'];

Cela vous montrera l'URL que vous avez été finalement redirigé vers.

test de cette extraits de code. Il fonctionne très bien pour moi:

$urls = array(
    'http://www.apple.com/imac',
    'http://www.google.com/'
);

$ch = curl_init();

curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

foreach($urls as $url) {
    curl_setopt($ch, CURLOPT_URL, $url);
    $out = curl_exec($ch);

    // line endings is the wonkiest piece of this whole thing
    $out = str_replace("\r", "", $out);

    // only look at the headers
    $headers_end = strpos($out, "\n\n");
    if( $headers_end !== false ) { 
        $out = substr($out, 0, $headers_end);
    }   

    $headers = explode("\n", $out);
    foreach($headers as $header) {
        if( substr($header, 0, 10) == "Location: " ) { 
            $target = substr($header, 10);

            echo "[$url] redirects to [$target]<br>";
            continue 2;
        }   
    }   

    echo "[$url] does not redirect<br>";
}

Si vous n'avez pas besoin du corps final, vous pouvez le faire de cette façon:

Set CURLOPT_HEADER et CURLOPT_NOBODY. L'en-tête « Emplacement » doit être retourné et contiendra la nouvelle URL. Effectuez ensuite la demande avec la nouvelle URL si nécessaire.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top