2009-11-06 7 views
5

Estoy usando curl para hacer que php envíe una solicitud http a algún sitio web en algún lugar y haya establecido CURLOPT_FOLLOWLOCATION en 1 para que siga los redireccionamientos. ¿Cómo puedo averiguar dónde se redirigió finalmente?Averiguar dónde se redirigió el curl

Respuesta

6

Usted puede hacer algo como:

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

Nice. No sabía sobre este. Teniendo en cuenta la cantidad de opciones de curl, no siempre es fácil encontrarlas. Gracias. –

-1

Si no necesita el cuerpo final puede hacerlo de esta manera:

Conjunto CURLOPT_HEADER y CURLOPT_NOBODY. Se debe devolver el encabezado "Ubicación" y contendrá la nueva url. A continuación, realice la solicitud con la nueva URL si es necesario.

2
$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']; 

Esto le mostrará la dirección URL que fueron finalmente redirigido a.

0

prueba estos fragmentos de código. Funciona bien para mí:

$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>"; 
} 
Cuestiones relacionadas