Warning: file_get_contents: failed to open stream: Redirection limit reached, aborting

前端 未结 4 1511
北海茫月
北海茫月 2020-12-03 22:40

I read over 20 related questions on this site, searched in Google but no use. I\'m new to PHP and am using PHP Simple HTML DOM Parser to fetch a URL. While this script works

4条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-03 23:14

    Had a similar problem today. I was using CURL and it wasn't returning my any error. Tested with file_get_contents() and I got...

    failed to open stream: Redirection limit reached, aborting in

    Made a few searches and I'v ended with this function that works on my case...

    function getPage ($url) {
    
    
    $useragent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.89 Safari/537.36';
    $timeout= 120;
    $dir            = dirname(__FILE__);
    $cookie_file    = $dir . '/cookies/' . md5($_SERVER['REMOTE_ADDR']) . '.txt';
    
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_FAILONERROR, true);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file);
    curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true );
    curl_setopt($ch, CURLOPT_ENCODING, "" );
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true );
    curl_setopt($ch, CURLOPT_AUTOREFERER, true );
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout );
    curl_setopt($ch, CURLOPT_TIMEOUT, $timeout );
    curl_setopt($ch, CURLOPT_MAXREDIRS, 10 );
    curl_setopt($ch, CURLOPT_USERAGENT, $useragent);
    curl_setopt($ch, CURLOPT_REFERER, 'http://www.google.com/');
    $content = curl_exec($ch);
    if(curl_errno($ch))
    {
        echo 'error:' . curl_error($ch);
    }
    else
    {
        return $content;        
    }
        curl_close($ch);
    
    }
    

    The website was checking for a valid user agent and for cookies.

    The cookie issue was causing it! :) Peace!

提交回复
热议问题