2010-12-01 7 views

Respuesta

14

Puede realizar una solicitud con cURL en lugar de file_get_contents().

Algo como esto debería funcionar ...

$ch = curl_init(); 
curl_setopt($ch, CURLOPT_URL, $url); 
curl_setopt($ch, CURLOPT_HEADER, TRUE); 
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, FALSE); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); 
$a = curl_exec($ch); 
if(preg_match('#Location: (.*)#', $a, $r)) 
$l = trim($r[1]); 

Source

+1

Gracias .. Pero dónde puedo obtener la salida HTML, entonces? Dentro de $ a solo puedo ver los encabezados. ¿Es posible obtener todo con solo una solicitud? editar: bien, eso fue estúpido. Ahora lo entiendo, habrán 2 solicitudes de todos modos = D. ¡Gracias! – HappyDeveloper

+0

pero ¿y si hay múltiples redirecciones? cómo obtener la URL final? – Aliweb

+1

CURL no está disponible en el motor de la aplicación Google, por lo que la respuesta no ayuda si necesita usar file_get_contents() –

17

Todo en una función:

function get_web_page($url) { 
    $res = array(); 
    $options = array( 
     CURLOPT_RETURNTRANSFER => true,  // return web page 
     CURLOPT_HEADER   => false, // do not return headers 
     CURLOPT_FOLLOWLOCATION => true,  // follow redirects 
     CURLOPT_USERAGENT  => "spider", // who am i 
     CURLOPT_AUTOREFERER => true,  // set referer on redirect 
     CURLOPT_CONNECTTIMEOUT => 120,  // timeout on connect 
     CURLOPT_TIMEOUT  => 120,  // timeout on response 
     CURLOPT_MAXREDIRS  => 10,  // stop after 10 redirects 
    ); 
    $ch  = curl_init($url); 
    curl_setopt_array($ch, $options); 
    $content = curl_exec($ch); 
    $err  = curl_errno($ch); 
    $errmsg = curl_error($ch); 
    $header = curl_getinfo($ch); 
    curl_close($ch); 

    $res['content'] = $content;  
    $res['url'] = $header['url']; 
    return $res; 
} 
print_r(get_web_page("http://www.example.com/redirectfrom")); 
+0

Ten cuidado. CURLOPT_FOLLOWLOCATION no está permitido cuando "open_base_dir" está lleno o cuando safe_mode está habilitado. – czjvic

47

Si es necesario utilizar file_get_contents() en lugar de rizo, no siguen redirige automáticamente:

$context = stream_context_create(
    array(
     'http' => array(
      'follow_location' => false 
     ) 
    ) 
); 

$html = file_get_contents('http://www.example.com/', false, $context); 

var_dump($http_response_header); 

respuesta inspirada por: How do I ignore a moved-header with file_get_contents in PHP?

+4

+1 Para usar file_get_contents –

+2

¿de dónde sacaste '$ http_response_header'? –

+4

@PetrPeller Esta es una variable especial de PHP: http://php.net/manual/en/reserved.variables.httpresponseheader.php –

0

Una solución completa con el desnudo file_get_contents (tenga en cuenta el parámetro de entrada-salida $url):

function get_url_contents_and_final_url(&$url) 
{ 
    do 
    { 
     $context = stream_context_create(
      array(
       "http" => array(
        "follow_location" => false, 
       ), 
      ) 
     ); 

     $result = file_get_contents($url, false, $context); 

     $pattern = "/^Location:\s*(.*)$/i"; 
     $location_headers = preg_grep($pattern, $http_response_header); 

     if (!empty($location_headers) && 
      preg_match($pattern, array_values($location_headers)[0], $matches)) 
     { 
      $url = $matches[1]; 
      $repeat = true; 
     } 
     else 
     { 
      $repeat = false; 
     } 
    } 
    while ($repeat); 

    return $result; 
} 
Cuestiones relacionadas