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

Mary-Kate Olsen
Release: 2024-10-31 10:43:02
Original
848 people have browsed it

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:

<code class="php">$context = stream_context_create(
    array(
        'http' => array(
            'follow_location' => false
        )
    )
);

$html = file_get_contents('http://www.example.com/', false, $context);</code>
Copy after login

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:

<code class="php">var_dump($http_response_header);</code>
Copy after login

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?"

The above is the detailed content of How to Retrieve the Actual URL after Redirection with file_get_contents()?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!