2011-12-30 89 views
5

我爲網頁的HTTP代碼創建了以下PHP函數。PHP CURL跟隨重定向獲取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; 
} 

我怎麼能修改此功能來跟蹤301個& 302重定向(可能性多次重定向),並獲得最終的HTTP狀態代碼?

+0

可能重複[Make curl follow redirects?](http://stackoverflow.com/questions/3519939/make-curl-follow-redirectcts) – 2013-02-13 00:39:32

回答

17

set CURLOPT_FOLLOWLOCATION to 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 

如果你不是捲曲的話,你可以用標準的PHP http wrappers來做到這一點(甚至可能在內部捲曲)。示例代碼:

$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"; 

另請參閱HEAD first with PHP Streams

一個相關的問題是How can one check to see if a remote file exists using PHP?

+0

很好的答案。在我的情況下,我需要最終的位置,所以做一個'sscanf($ header,'Location:%s',$ loc);'做了訣竅。謝謝! – noinput 2015-03-14 05:59:56