file_get_contents через прокси - PullRequest
       15

file_get_contents через прокси

0 голосов
/ 21 октября 2011

Я хочу прочитать некоторые страницы / сайты из Интернета, используя file_get_contents и прокси. Я придумал следующий код:

$ opts = array ('http' => array ('proxy' => '14 .199.56.205: 8909 ', 'request_fulluri' => true));

$ context = stream_context_create ($ opts);

$ test = file_get_contents ('http://www.google.com', false, $ context);

echo $ test;

Я взял прокси из списка, расположенного здесь http://www.hidemyass.com/proxy-list/

Я тестировал прокси, и он работает из браузера, но с file_get_contents я просто получаю пустую страницу.

Где ошибка? :)

1 Ответ

0 голосов
/ 07 января 2017

Бесплатные прокси бьют или пропускают и регулярно терпят неудачу по той или иной причине.Вот функция, которую я использую, которая случайным образом попробует 2 прокси из массива прокси, ищущих HTTP 200. В качестве последнего средства он использует 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;

}
...