2012-11-26 48 views
1

我有一個腳本,它需要一個some.txt文件並讀取鏈接並返回,如果我的網站反向鏈接是否存在。但問題是,速度很慢,我想提高速度。有什麼方法可以提高速度嗎?提高我的腳本的速度

<?php 
ini_set('max_execution_time', 3000); 
$source = file_get_contents("your-backlinks.txt"); 
$needle = "http://www.submitage.com"; //without http as I have imploded the http later in the script 
$new = explode("\n",$source); 
foreach ($new as $check) { 
$a = file_get_contents(trim($check)); 
if (strpos($a,$needle)) { 
$found[] = $check; 
    } else { 
    $notfound[] = $check; 
      } 
         } 
echo "Matches that were found: \n ".implode("\n",$found)."\n"; 
echo "Matches that were not found \n". implode("\n",$notfound); 
?> 
+0

不,它取決於網絡,你無法控制。 –

+0

@ N.B。是正確的。最大的問題將是網絡,但使用strpos可能是另一種解決方案。您可以簡單地在返回的內容中檢查您的域名的位置,而不是分割整個字符串。你可能需要做一些調查,但值得一試? – Gavin

+0

您應該使用異步HTTP。但是,我無法找到如何在PHP中執行此操作的好源代碼。 –

回答

0

通過優化PHP,除了可能使用某些人造多線程解決方案之外,您無法再從操作中擠出更多速度。

但是,您可以創建一個隊列系統,使您可以將檢查作爲後臺任務運行。您不必在遍歷它們時檢查URL,而是將它們添加到隊列中。然後編寫一個cron腳本,從隊列中逐一獲取未經檢查的URL,檢查它們是否包含對域的引用並保存結果。

2

您最大的瓶頸是您按順序執行HTTP請求,而不是並行執行。 curl能夠並行執行多個請求。這裏有一個來自the documentation的例子,它很適合使用循環並實際收集結果。我不能承諾這是正確的,我只承諾我已經正確地遵循了文檔:

$mh = curl_multi_init(); 
$handles = array(); 

foreach($new as $check){ 
    $ch = curl_init(); 
    curl_setopt($ch, CURLOPT_URL, $check); 
    curl_setopt($ch, CURLOPT_HEADER, 0); 
    curl_multi_add_handle($mh,$ch); 
    $handles[$check]=$ch; 
} 

// verbatim from the demo 
$active = null; 
//execute the handles 
do { 
    $mrc = curl_multi_exec($mh, $active); 
} while ($mrc == CURLM_CALL_MULTI_PERFORM); 

while ($active && $mrc == CURLM_OK) { 
    if (curl_multi_select($mh) != -1) { 
     do { 
      $mrc = curl_multi_exec($mh, $active); 
     } while ($mrc == CURLM_CALL_MULTI_PERFORM); 
    } 
} 
// end of verbatim code 

for($handles as $check => $ch){ 
    $a = curl_multi_getcontent($ch) 
    ... 
}