2011-12-30 19 views
5

Creé la siguiente función de PHP para el código HTTP de una página web.PHP CURL seguir redirigir para obtener el estado HTTP

function get_link_status($url, $timeout = 10) 
{ 
    $ch = curl_init(); 

    // set cURL options 
    $opts = array(CURLOPT_RETURNTRANSFER => true, // do not output to browser 
       CURLOPT_URL => $url,   // set URL 
       CURLOPT_NOBODY => true,   // do a HEAD request only 
       CURLOPT_TIMEOUT => $timeout); // set timeout 
    curl_setopt_array($ch, $opts); 

    curl_exec($ch); // do it! 

    $status = curl_getinfo($ch, CURLINFO_HTTP_CODE); // find HTTP status 

    curl_close($ch); // close handle 

    return $status; 
} 

¿Cómo puedo modificar esta función para seguir & 301 302 redirecciones (posibilidad múltiples redirecciones) y obtener el código de estado HTTP final?

+0

posible duplicado de [Hacer currar seguir redirige?] (Http://stackoverflow.com/questions/3519939/make-curl-follow-redirects) –

Respuesta

17

conjunto CURLOPT_FOLLOWLOCATION a TRUE.

$opts = array(CURLOPT_RETURNTRANSFER => true, // do not output to browser 
       CURLOPT_URL => $url,   // set URL 
       CURLOPT_NOBODY => true,   // do a HEAD request only 
       CURLOPT_FOLLOWLOCATION => true // follow location headers 
       CURLOPT_TIMEOUT => $timeout); // set timeout 

Si no está obligado a curvarse, se puede hacer esto con las envolturas de PHP HTTP estándar, así (que podría ser incluso rizar entonces internamente). Código de ejemplo:

$url = 'http://example.com/'; 
$code = FALSE; 

$options['http'] = array(
    'method' => "HEAD" 
); 

$context = stream_context_create($options); 

$body = file_get_contents($url, NULL, $context); 

foreach($http_response_header as $header) 
{ 
    sscanf($header, 'HTTP/%*d.%*d %d', $code); 
} 

echo "Status code (after all redirects): $code<br>\n"; 

Véase también HEAD first with PHP Streams.

Una pregunta relacionada es How can one check to see if a remote file exists using PHP?.

+0

gran respuesta. en mi caso, necesitaba la ubicación final, por lo que hacer 'sscanf ($ header, 'Location:% s', $ loc);' fue el truco. ¡gracias! – noinput

Cuestiones relacionadas