Home >Backend Development >PHP Tutorial >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:
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!