2010-01-30 132 views
1

我希望我的捲曲使用隨機代理從與該格式保存在我的網站上proxy.txt文件:如何隨機分配代理捲曲?

1.1.1.1:8080 
2.2.2.2:8080 
3.3.3.3:8080 
... 

我想它,使其隨機這樣每次它使用來自不同代理proxy.txt列表,但我不知道我可以在php中編寫類似的代碼。

回答

1

從文件中讀取一個隨機行:

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; 
} 
0

遲到了,但想分享這個:

基本上靜態變量$proxys只會被設置一次,並且會記住數組指針,所以每次調用change_proxy()時它都會給你下一個文件,然後返回到開頭s循環一次。

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; 
}