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>
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>
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!