2013-03-21 50 views
1

我有一個網址陣列(約1000個網址),如果它們存在或不存在,我想檢查它們。這裏是我當前的代碼:檢查1000個網址是否存在,是否有快捷方式?

$south_east_png_endings = array(); 
for($x=1;$x<=25;$x++) { 
    for($y=1;$y<=48;$y++) { 
     $south_east_png_endings[] ="${x}s${y}e.png"; 
    } 
} 

foreach ($south_east_png_endings as $se){ 
    $url = 'http://imgs.xkcd.com/clickdrag/'.$se; 
    $file_headers = @get_headers($url); 
    if($file_headers[0] == 'HTTP/1.1 404 Not Found') { 
     // echo 'Does not exist'; 
    } 
    else 
    { 
     echo $url; 
    } 
} 

這個腳本,但它回聲了所有的工作的網址,但過程太長(需要幾分鐘才能完成)。有沒有辦法更快地做到這一點,或者這樣做的速度如此之快?也許我可以使用curl_timeout函數來縮短時間?

+0

我推薦到餐桌的過程:http://chemicaloliver.net/programming/speeding-up-php-using-process-forking-for-image-resizing/ – 2013-03-21 07:52:58

回答

3

1)get_headers()實際上使用GET請求,如果您只想知道文件是否存在,則不需要GET請求。使用HEAD代替,example from the manual

<?php 
// By default get_headers uses a GET request to fetch the headers. If you 
// want to send a HEAD request instead, you can do so using a stream context: 
stream_context_set_default(
    array(
     'http' => array(
      'method' => 'HEAD' 
     ) 
    ) 
); 
$headers = get_headers('http://example.com'); 
?> 

2),因爲這些檢查可以並行輕鬆運行,您應該使用單獨的線程/進程做檢查。但是,如果您是在家中完成此操作,則您的路由器可能會一次阻塞1000個請求,因此您可能需要使用5-20個併發線程。

0

對於並聯檢查,您可以使用multi_curl。它可能相當快。這裏有一些example。因爲它比@eis的例子更復雜。

P.S.也可以使用curl來使用HEAD方法。

0
function _isUrlexist($url) { 
    $flag = false; 
    if ($url) { 
     $ch = curl_init(); 
     curl_setopt_array($ch, array(
      CURLOPT_URL => $url, 
      CURLOPT_RETURNTRANSFER => true, 
      CURLOPT_NOBODY => true, 
      CURLOPT_HEADER => true 
      )); 
     curl_exec($ch); 
     $info = curl_getinfo($ch, CURLINFO_HTTP_CODE); 
     curl_close($ch); 

     $flag = ($info == 200) ? true : false; 
    } 
    return $flag; 
} 
+0

儘管此代碼可能會有助於解決問題, 提供關於_why_和/或_how_的其他上下文回答問題將顯着提高其 的長期價值。請[編輯]你的答案,添加一些 的解釋。特別是,它是否遵循301和/或302重定向,或者僅僅報告失敗? – 2016-07-08 11:33:25

相關問題