很多 PHP 開啟檔案的函式包括 file()
, fopen()
, file_get_contents()
等等,除了開啟本機硬碟中的檔案,也可以開啟網絡上的資源,例如:
1
2
3
|
$lines = file('http://www.example.com/');
$handle = fopen('http://www.example.com/', "r");
$homepage = file_get_contents('http://www.example.com/');
|
你是否見過以下的錯誤呢?
1
2
|
PHP Warning: file_get_contents(http://example.org/):
failed to open stream: Redirection limit reached, aborting
|
Christian Weiske 發現原來 PHP 跟蹤 URL 重定向 (URL redirection) 有次數限制,並提出了解決辦法。
以上顯示的錯誤訊息表示你輸入的 URL 送回一個 HTTP Location:
標頭,表示真正的資料放在另一個 URL,當 PHP 追蹤到第二個 URL 的時候,它卻告訴 PHP 需要到第三個 URL 找尋,如是者繼續下去……重複了 20 次,這時 PHP 舉手投降,拒絕再跟蹤下去,並送回一個錯誤訊息給你。
同樣會導致 URL 重定向的 HTTP 標頭包括:
如果你要開啟的檔案有機會需要超過 20 次 URL 重定向才找得到,可以修改 HTTP stream context
中的 max_redirects
選項:
1
2
3
4
5
6
7
8
9
10
|
<?php
$context = stream_context_create(
array(
'http' => array(
'max_redirects' => 101
)
)
);
$content = file_get_contents('http://example.org/', false, $context);
?>
|
必須注意假如 max_redirects
的值為 1 或以下,表示不追蹤 URL 重定向。
你也可以完全不追蹤 URL 重定向,只要設定 follow_location
便可以:
1
2
3
4
5
6
7
8
9
10
|
<?php
$context = stream_context_create(
array(
'http' => array(
'follow_location' => false
)
)
);
$content = file_get_contents('http://example.org/', false, $context)
?>
|