【发布时间】:2010-01-30 18:09:38
【问题描述】:
我希望我的 curl 使用 proxy.txt 文件中的随机代理,该文件以这种格式保存在我的站点中:
1.1.1.1:8080
2.2.2.2:8080
3.3.3.3:8080
...
我希望它随机生成,以便每次它使用 proxy.txt 列表中的不同代理,但我不知道我可以在 php 中编写类似的代码。
【问题讨论】:
我希望我的 curl 使用 proxy.txt 文件中的随机代理,该文件以这种格式保存在我的站点中:
1.1.1.1:8080
2.2.2.2:8080
3.3.3.3:8080
...
我希望它随机生成,以便每次它使用 proxy.txt 列表中的不同代理,但我不知道我可以在 php 中编写类似的代码。
【问题讨论】:
从文件中随机读取一行:
srand ((double)microtime()*1000000);
$f_contents = file ("proxy.txt");
$line = $f_contents[array_rand ($f_contents)];
print $line;
你现在只需要:
function get_random_proxy()
{
srand ((double)microtime()*1000000);
$f_contents = file ("proxy.txt");
$line = $f_contents[array_rand ($f_contents)];
return $line;
}
【讨论】:
聚会迟到了,但想分享这个:
基本上静态变量$proxys只被设置一次,并记住数组指针,所以每次你调用change_proxy()它都会给你文件中的下一个,然后在它循环一次后返回开始。
function change_proxy()
{
static $proxys = file('./proxy.txt', FILE_SKIP_EMPTY_LINES|FILE_IGNORE_NEW_LINES);
$proxy = current($proxys);
$end = next($proxys); # false when end
if(!$end) {
reset($proxys);
}
return $proxy;
}
【讨论】: