从重定向的 url 获取来源 HTML

Getting the source HTML from an url that redirects

我正在尝试从 html 页面获取用户名。 但是,此页面进行了重定向,我的函数在 return.

中给出了 NULL
function getSGname($steamid) {
/*
 * Get the user's name from SteamGifts.com
 *
 * @param bigint $steamid SteamID64
 * @return false|string SteamGifts user's name
 *
 */
    set_time_limit('30');

    // Include DOM library
    include('/lib/simple_html_dom.php');

    # create object
    $html = new simple_html_dom();

    // Build the URL to the user's SteamGifts profile
    $url = "http://www.steamgifts.com/user/id/$steamid";

    #### CURL BLOCK ####

    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);

    $content = curl_exec($curl);
    curl_close($curl);

    # note the variable change.
    $string = str_get_html($content);

    // Some code here to get certain div from the string
    // ...

    return $string;
}

echo "name: " . getSGname('76561197962290563');

现在,如果我将 url 替换为另一个站点,它就可以正常工作了。

$url = "http://www.bundlequest.com/index.php";

虽然我什至没有收到错误。 为什么我没有收到第一个 url 的任何信息,我该如何解决?

Curl 将自动跟随重定向。您需要将 CURLOPT_FOLLOWLOCATION 设置为 false 并手动处理重定向。

正如 Paul 所说,解决方案是将 CURLOPT_FOLLOWLOCATION 设置为 false。

curl_error 上的警告:在显示 curl_error 之前关闭 $curl 使用:

curl_close($curl);

希望对您有所帮助。

这可能是因为该站点要使用 cookie,因此该网站一直重定向,因为它没有设置 cookie 文件。

替换为:

curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);

与:

curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($curl, CURLOPT_AUTOREFERER, true);
curl_setopt($curl, CURLOPT_MAXREDIRS, 10);
curl_setopt($curl, CURLOPT_COOKIEJAR, 'cookie.txt');

您需要 CURLOPT_COOKIEJAR 选项来设置 cookie 文件。 CURLOPT_MAXREDIRS 是允许的最大重定向。 10个应该够了。

如果它仍然给你一个错误,你可以使用:

if($errno = curl_errno($curl)) {
    echo $errno;
}

这会显示错误代码