How to capture redirected pages using php file_get_contents

You can use the third parameter of the file_get_contents function to retrieve the content of a redirected page.

The sample code is provided below:

$url = 'https://example.com'; // 重定向前的URL

$context = stream_context_create([
    'http' => [
        'follow_location' => true, // 启用重定向
        'max_redirects' => 10 // 最大重定向次数
    ]
]);

$content = file_get_contents($url, false, $context);

echo $content;

In the example above, we created a $context and passed it to the file_get_contents function using the stream_context_create function. The http options in $context are set to follow_location and max_redirects for enabling redirection and setting the maximum number of redirects.

Next, we use the file_get_contents function to retrieve the content of the redirected page and store it in the $content variable. Finally, we use the echo statement to display the retrieved content.

Please note that when using the file_get_contents function to fetch remote content, make sure that the necessary configurations are correctly set and the server allows this operation. If you are unable to retrieve the content of redirected pages, consider using alternative methods such as the cURL library.

bannerAds