使用CURL从重定向的URL抓取网页


Grab web pages from redirected URL using CURL

我有一个urlhttp://www.example.com/all.php?f=1.当我打开url时,它重定向到http://www.example.com/all.php其值为f(其中f=1)。我尝试使用curl获取重定向的URL,但仍然失败。我试着在这个网站上搜索任何东西,但几乎所有的问题都是关于如何获得网址,而不是如何获取。

我尝试这个功能:

function get_url_content($url,$timeout) {
        $ch = curl_init($url); // initialize curl with given url
        curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER["HTTP_USER_AGENT"]); // set  useragent
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); // write the response to a variable
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE); // follow redirects if any
        curl_setopt($ch, CURLOPT_MAXREDIRS, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout); // max. seconds to execute
        curl_setopt($ch, CURLOPT_FAILONERROR, 1); // stop when it encounters an error
        $output = curl_exec($ch);
        curl_close($ch);
        if (!$output) {
            return -1;
        }
        return $output;
}

但当我运行它时:

$url = 'http://www.example.com/all.php?f=1';
$me = get_url_content($url);
echo $me; //it should grab the page http://www.example.com/all.php

它返回-1,这意味着没有输出。我对此感到困惑。有什么解决办法吗?

将其更改为

$url = 'http://www.example.com/';
$me = file_get_content($url);
echo $me;