简体   繁体   中英

file_get_contents returns HTTP/1.1 301 Moved Permanently

I want to get the contents of the url, when I used file_get_contents method it returns HTTP/1.1 301 Moved Permanently. But in browser the link works fine.

I also tried curl function, but it is returns the same problem. The code is

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $page_url);
curl_setopt($ch, CURLOPT_HEADER, TRUE);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$a = curl_exec($ch);
if(preg_match('#Location: (.*)#', $a, $r))
$xx = trim($r[1]);

Thanks in advance!

更改以下内容,因为curl应该能够跟随重定向curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);

Try this

    $ch= curl_init();
    curl_setopt ($ch, CURLOPT_URL, $page_url );
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch,CURLOPT_VERBOSE,1);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 1.0.3705; .NET CLR 1.1.4322; Media Center PC 4.0)');
    curl_setopt ($ch, CURLOPT_REFERER,'http://www.google.com');  //just a fake referer
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch,CURLOPT_POST,0);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
    $htmlContent= curl_exec($ch);
    curl_close($ch);

Thanks for all of you. I found the answer for my question.

$opts = array('http'=>array('header' => "User-Agent:Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)\r\n"));
$context = stream_context_create($opts);
$buffer = file_get_contents($row['url'],false,$context);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM