file_get_contents and redirect

75 views Asked by At

Using file_get_contents I get the wrong page. I am sending a request with a header to the page https://soccer365.ru/games/1906341 /, and I get https://soccer365.ru/games/1906388/

How do I get exactly the page without a redirect?

        $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;

Using file_get_contents I get the wrong page. I am sending a request with a header to the page https://soccer365.ru/games/1906341 /, and I get https://soccer365.ru/games/1906388/

1

There are 1 answers

1
talha2k On

It is possible that this website might be performing a redirect based on some logic such as user-agent, cookies, or other header information. You can check if the server is sending a redirect status code. You can do this by setting the $http_response_header variable to get the response headers and then inspecting them:

$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";
}

In some cases, you can try to disable following redirects. However, this isn't directly supported by file_get_contents. Instead, you might need to switch to using cURL, which provides more control over HTTP requests, including the ability to handle or ignore redirects:

$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;