首頁  >  文章  >  後端開發  >  在 PHP 中使用 file_get_contents() 時如何取得重定向後的最終 URL?

在 PHP 中使用 file_get_contents() 時如何取得重定向後的最終 URL?

Linda Hamilton
Linda Hamilton原創
2024-10-28 09:52:29227瀏覽

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

File_Get_Contents:揭示最終URL

問題: 使用file_get_contents() 抓取內容時,您遇到重定向,但希望發現真實URL .

解決方案:

雖然file_get_contents() 通常處理重定向,但如果您明確需要控制,請採用以下方法:

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

透過將'follow_location' 設為false,可以防止file_get_contents() 自動追蹤重定向。回應標頭(在 $http_response_header 中提供)將包含「Location」標頭,指示任何重定向後的真實 URL。

提示: 此方法的靈感來自於如何做中提供的解決方案我在 PHP 中忽略了帶有 file_get_contents 的移動標頭?

以上是在 PHP 中使用 file_get_contents() 時如何取得重定向後的最終 URL?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn