"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Retrieve the Actual URL after Redirection with file_get_contents()?

How to Retrieve the Actual URL after Redirection with file_get_contents()?

Published on 2024-11-12
Browse:217

How to Retrieve the Actual URL after Redirection with file_get_contents()?

Retrieving the Actual URL after File Retrieval with file_get_contents

When using file_get_contents() to retrieve website content, it's possible that the provided URL redirects to a different location. While this feature can be convenient, it can also create a need to determine the actual URL reached after redirection.

One method to achieve this is by configuring file_get_contents() to ignore redirects. Here's how:

$context = stream_context_create(
    array(
        'http' => array(
            'follow_location' => false
        )
    )
);

$html = file_get_contents('http://www.example.com/', false, $context);

By setting 'follow_location' to false in the stream context, file_get_contents() will retrieve the content without automatically following redirections.

After making the request, the headers returned during the HTTP response can be examined to obtain the final URL:

var_dump($http_response_header);

This will display an array containing the HTTP headers, including the 'Location' header that indicates the actual URL reached after any redirects.

This approach is inspired by the solution provided on Stack Overflow in the thread "How do I ignore a moved-header with file_get_contents in PHP?"

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3