php file_get_contents和重定向

whlutmcx  于 5个月前  发布在  PHP
关注(0)|答案(1)|浏览(60)

使用file_get_contents我得到了错误的页面。我向页面https://soccer365.ru/games/1906341/发送了一个带有头部的请求,我得到了https://soccer365.ru/games/1906388/
如何在没有重定向的情况下准确获取页面?

$options = array(
            'http' => array(
                'method' => "GET",
                'header' =>
                "Accept-language: ru-RU,ru;q=0.9,en-US;q=0.8,en;q=0.7\r\n" .
                    "Cache-Control:no-cache" .
                    "Pragma:" . rand(1,74628239) .
                    "Referer:https://soccer365.ru/" .
                    'Sec-Ch-Ua:"Opera";v="105", "Chromium";v="119", "Not?A_Brand";v="24"' .
                    "Sec-Ch-Ua-Mobile:?0" .
                    'Sec-Ch-Ua-Platform:"Windows"' .
                    "Sec-Fetch-Mode:no-cors" .
                    "Sec-Fetch-Site:cross-site" .
                    "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36 OPR/105.0.0.0 (Edition Yx)"
            )
        );

         $url_game_goals = file_get_contents("https://soccer365.ru/games/1906341/" . $value_games . "/", false, $context);
         
         echo $url_game_goals;

字符串
使用file_get_contents我得到了错误的页面。我向页面https://soccer365.ru/games/1906341/发送了一个带有头部的请求,我得到了https://soccer365.ru/games/1906388/

vxqlmq5t

vxqlmq5t1#

此网站可能会基于某些逻辑执行重定向,例如user-agent,cookie或其他标头信息。您可以检查服务器是否正在发送重定向状态代码。您可以通过设置$http_response_header变量来获取响应标头,然后检查它们:

$options = [
    'http' => [
        // your options...
    ]
];

$context = stream_context_create($options);
$content = file_get_contents('https://soccer365.ru/games/1906341/', false, $context);

foreach ($http_response_header as $header) {
    echo $header . "\n";
}

字符串
在某些情况下,您可以尝试禁用以下重定向。但是,file_get_contents不直接支持此操作。相反,您可能需要切换到使用cURL,它提供了对HTTP请求的更多控制,包括处理或忽略重定向的能力:

$ch = curl_init('https://soccer365.ru/games/1906341/');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false); // Don't follow redirects
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    "Accept-language: ru-RU,ru;q=0.9,en-US;q=0.8,en;q=0.7",
    // put your other headers...
]);
$content = curl_exec($ch);
curl_close($ch);

echo $content;

相关问题