我想通过使用file_get_contents和代理从互联网上读取一些页面/网站。我写了下面的代码:
选择美元=数组("http"=>阵列("代理"=>"14.199.56.205:8909",'request_fulluri' => true));
$context = stream_context_create($opts);
$test = file_get_contents('http://www.google.com', false, $context);
echo $测试;
我从这里的列表中获取代理http://www.hidemyass.com/proxy-list/
我测试了代理,它是从浏览器工作,但与file_get_contents我只是收到空白页。
错误在哪里?:)
免费代理是命中或失败的,并且经常因为这样或那样的原因失败。下面是我使用的一个函数,它将随机尝试从代理数组中寻找HTTP 200的2个代理。作为最后的手段,它使用anonymouse.org获取文件。
function proxy($url) {
$proxies = array();
$proxies[] = '1.1.1.1:80';
$proxies[] = '1.1.1.1:80';
$proxies[] = '1.1.1.1:80';
$proxies[] = '1.1.1.1:80';
$proxies[] = '1.1.1.1:80';
$proxies[] = '1.1.1.1:80';
$http=0;
$try=0;
while (true) {
$proxy = $proxies[array_rand($proxies)];
if (!function_exists('curl_init')) { die('Sorry cURL is not installed!'); }
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_REFERER, "http://www.yomamma.com/");
curl_setopt($ch, CURLOPT_USERAGENT, "MozillaXYZ/1.0");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_PROXY, $proxy);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
$output = curl_exec($ch);
$http = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($http==200) { break; }
$try++;
if($try>2) { break; }
}
if ($http!=200) {
$output=file_get_contents("http://anonymouse.org/cgi-bin/anon-www.cgi/$url");
}
return $output;
}
现在大多数网站都使用HTTPS。因此,在您的$opts
变量中,您应该使用'HTTPS'而不是'HTTP'。