接上一篇文章《用linux的curl实现自动投票 》!
为了提高投票速度,用PHP函数popen代替exec,它相当于把curl的执行推到了后台去运行,每推一次,增加一个进程。
<?php
/*
* 多进程投票程序
* author: 木鱼
* blog: http://muyu.iteye.com/
*
* 关于多进程的代码参考了 回忆未来[张宴] http://blog.s135.com/post/311/
*/
/*------------获取proxy--------------*/
$result = array();
/*----------(1) mfxk.com---------*/
echo "\n";
$urlList = array(
'http://www.mfxk.com/article/daili/54527.html',
'http://www.mfxk.com/article/daili/54470.html',
'http://www.mfxk.com/article/daili/54434.html',
);
foreach($urlList as $url) {
echo "\nParsing web page: {$url}";
$tmpHtml = file_get_contents($url);
preg_match_all("/ (\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}) (\d{1,4}) /i", $tmpHtml, $matches);
for ($i=0; $i< count($matches[0]); $i++) {
$result[] = $matches[1][$i] . ":" . $matches[2][$i];
}
}
/*----------(2) 996i.cn---------*/
echo "\n";
$urlList = array(
'http://www.996i.cn/ip/sort033/7542.html',
'http://www.996i.cn/ip/sort033/7520.html',
'http://www.996i.cn/ip/sort033/7488.html',
'http://www.996i.cn/ip/sort033/7487.html',
);
foreach($urlList as $url) {
echo "\nParsing web page: {$url}";
$tmpHtml = file_get_contents($url);
preg_match_all("/\s+(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\s+(\d{1,4})\s+/i", $tmpHtml, $matches);
for ($i=0; $i< count($matches[0]); $i++) {
$result[] = $matches[1][$i] . ":" . $matches[2][$i];
}
}
/*------------去重--------------*/
$result = array_unique($result);
echo "\n\nParse excuted successfully!";
echo "\nTotal proxy:\t" . count($result);
/*------------多进程投票--------------*/
echo "\n\n\nStart to vote:";
$proxyList = $result;
while(!empty($proxyList)) {
$proxy = array_shift($proxyList);
run($proxy);
}
echo "\ndone!\n";
function run($proxy) {
global $p_number;
if ($p_number <= 0) {
$p_number = worker_processes($p_number);
}
$p_number = $p_number - 1;
$out = popen("curl -m 30 -x {$proxy} -d \"id=1234\" http://www.example.com/VoteAction.php &", "r");
pclose($out);
}
function worker_processes($p_number) {
$limit = 50;//允许推到后台的最大进程数
while ($p_number <= 0)
{
$cmd = popen("ps -ef | grep \"example.com\" | grep -v grep | wc -l", "r");
$line = fread($cmd, 512);
pclose($cmd);
$p_number = $limit - $line;
if ($p_number <= 0) {
sleep(1);//暂停1秒钟
}
}
return $p_number;
}