2012-09-13 71 views
0

我該如何讓這個腳本可以使用多線程? 已經嘗試過所有的教程,但沒有成功:( ,什麼是最大的線程數,我可以捲曲的PHP使用?如何使用多線程的php curl?

<?php 
$imput = file("$argv[1]"); 
$output = $argv[2]; 


foreach ($imput as $nr => $line) { 
$line = trim($line); 
print ("$nr - check :" . $line . "\r\n"); 

$check = ia_continutul($line); 

if (strpos($check,'wordpress') !== false) { 

    $SaveFile = fopen($output, "a"); 
    fwrite($SaveFile, "$line\r\n"); 
    fclose($SaveFile); 
    } 
} 
print "The END !\r\n"; 

function ia_continutul($url) { 
    $ch = curl_init(); 
    $timeout = 3; 
    curl_setopt($ch,CURLOPT_URL,$url); 
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,1); 
    curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout); 
    curl_setopt($ch, CURLOPT_TIMEOUT, 5); 
    $data = curl_exec($ch); 
    curl_close($ch); 
    return $data; 
} 
?> 
+0

http://php.net/manual/en/function.curl-multi-exec.php –

+1

PHP不是多線程的,並且很可能永遠不會對語言進行根本性的重新設計。 –

回答

-2

你不能多線程PHP,這是一個腳本語言,因此腳本在一定的順序跑了,如果你有等待捲曲完成它會繼續加載,而出現這種情況,這就像一個睡眠(1)功能,在你的代碼。

有一些基本的東西,你可以爲了加快你的代碼的速度,不要在循環中執行mysql請求(我沒有看到任何內容),而是建立你的代碼p查詢然後在循環結束後執行。看看重構你的代碼,這樣你就可以做到最少的捲髮數量,因此速度很快。嘗試找到一種方法在循環之外進行卷曲。

4

可以在PHP多線程...

class Check extends Thread { 
    public function __construct($url, $check){ 
     $this->url = trim($url); 
     $this->check = $check; 
    } 
    public function run(){ 
     if (($data = file_get_contents($this->url))) { 
      if (strpos($data, "wordpress") !== false) { 
       return $this->url; 
      } 
     } 
    } 
} 
$output = fopen("output.file", "w+"); 
$threads = array(); 
foreach(file("input.file") as $index => $line){ 
    $threads[$index]=new Check($line, "wordpress"); 
    $threads[$index]->start(); 
} 
foreach($threads as $index => $thread){ 
    if(($url = $threads[$index]->join())){ 
    fprintf($output, "%s\n", $url); 
    } 
} 

https://github.com/krakjoe/pthreads