How Can I Get the Final URL After Redirects When Using file_get_contents() in PHP?

Linda Hamilton
Release: 2024-10-28 09:52:29
Original
294 people have browsed it

How Can I Get the Final URL After Redirects When Using file_get_contents() in PHP?

File_Get_Contents: Unveiling the Final URL

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>
Copy after login

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!

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