Home >Backend Development >PHP Tutorial >How Can I Get the Final URL After Redirects When Using file_get_contents() in PHP?
Problem: While scraping content using file_get_contents(), you encounter redirects but desire to uncover the true URL.
Solution:
Although file_get_contents() generally handles redirects, if you explicitly need control, employ the following approach:
<code class="php">// Disable automatic redirect following $context = stream_context_create([ 'http' => [ 'follow_location' => false ] ]); // Retrieve the content with no redirects $html = file_get_contents('http://www.example.com/', false, $context); // Access the HTTP response headers to determine the actual URL var_dump($http_response_header);</code>
By setting 'follow_location' to false, you prevent file_get_contents() from automatically following redirects. The response headers (available in $http_response_header) will contain the "Location" header, indicating the true URL after any redirects.
Tip: This approach is inspired by the solution provided in How do I ignore a moved-header with file_get_contents in PHP?
The above is the detailed content of How Can I Get the Final URL After Redirects When Using file_get_contents() in PHP?. For more information, please follow other related articles on the PHP Chinese website!