2012-11-26 46 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) 
    ... 
}