Home >Backend Development >PHP Tutorial >How to Get the Actual URL After Redirection Using file_get_contents()?

How to Get the Actual URL After Redirection Using file_get_contents()?

Susan Sarandon
Susan SarandonOriginal
2024-10-29 04:59:02817browse

How to Get the Actual URL After Redirection Using file_get_contents()?

Obtaining the Real URL After Redirection with file_get_contents

When fetching content from a URL using file_get_contents(), it can smoothly handle redirects to new URLs. However, sometimes it is necessary to determine the actual URL after the redirection occurs.

Is There a Solution?

To obtain the real URL after a redirect has taken place, a custom solution is required. File_get_contents() follows redirects by default, but this behavior can be overridden.

How to Override Redirect Behavior

To disable automatic redirection and obtain the actual URL:

  1. Create a stream context using stream_context_create().
  2. Set the 'follow_location' parameter to false to prevent automatic redirection.
  3. Use the modified stream context when calling file_get_contents().

Code Snippet:

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

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

var_dump($http_response_header);</code>

After disabling automatic redirection, the $http_response_header array will contain information about the actual URL visited, providing the necessary data for further processing.

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

Statement:
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