我试图弄清楚如何从列表中随机选择一个代理 ip,然后用它执行 curl,如果发生故障,请使用新的代理 ip。这是我没有随机化的工作代码:
$url = "www.example.com";
$loginpassw = 'myproxypw';
$proxy_ip = '23.27.37.128';
$proxy_port = '29842';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_PROXYPORT, $proxy_port);
curl_setopt($ch, CURLOPT_PROXY, $proxy_ip);
curl_setopt($ch, CURLOPT_PROXYUSERPWD, $loginpassw);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_AUTOREFERER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 600);
$html = curl_exec($ch);
if (strpos($html,'To continue, please type the characters below') !== false) {
echo "now an error has occurred, let's try a new proxy";
}
curl_close($ch);
理想情况下proxy_ip
和proxy_port
必须在说的列表中保持不变:
$proxylist = array (
array("ip" => "23.27.37.128", "port" => "29842"),
array("ip" => "23.27.37.111", "port" => "29852"),
array("ip" => "23.27.37.112", "port" => "29742"),
array("ip" => "23.27.37.151", "port" => "29242")
);
我想知道是否可以使用随机播放:
shuffle($proxylist);
while($element = array_pop($proxylist)){
return $element;
}
我的第二个问题将是最好的方法,我的 PHP 并不完美,所以我想知道而不是一遍又一遍地重写顶部卷曲,我应该将它存储在一个函数中吗?
任何帮助表示赞赏。
谢谢,西蒙
编辑:
以下代码似乎在我将代码分成两个函数的地方工作:
function curltime($url, $proxy_ip, $proxy_port, $loginpassw){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_PROXY, $proxy_ip);
curl_setopt($ch, CURLOPT_PROXYUSERPWD, $loginpassw);
curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 0);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_AUTOREFERER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 600);
return curl_exec($ch);
curl_close($ch);
}
//now let's do the curl
$url = "www.example.com";
$proxylist = array (
array("proxyip" => "23.27.37.128", "proxyport" => "29842"),
array("proxyip" => "23.27.37.111", "proxyport" => "29852"),
array("proxyip" => "23.27.37.112", "proxyport" => "29742"),
array("proxyip" => "23.27.37.151", "proxyport" => "29242")
);
foreach ($proxylist[mt_rand(0,count($proxylist)-1)] as $key => $value) {
$$key = $value;
}
$html = $this->curltime($url, $proxyip, $proxyport, 'somepassword');
if (strpos($html,'To continue, please type the characters below') !== false) {
echo "now we have errors so let's try again"
foreach ($proxylist[mt_rand(0,count($proxylist)-1)] as $key => $value) {
$$key = $value;
}
$html = $this->curltime($url, $proxyip, $proxyport, 'somepassword');
}
$cache .= $html;