只要在 php.ini 檔案中啟用了 allow_url_fopen 選項,就可以在大多數需要用檔案名稱作為參數的函數中使用 HTTP 和 FTP 的 URL 來代替檔案名稱。同時,也可以在 include、include_once、 require 及 require_once 語句中使用 URL。PHP 所支援協議的更多資訊參見支援的協議和封裝協議。
注意:
要在 PHP 4.0.3 及其更早的版本中使用 URL 封裝協議,需要在編譯時間用 --enable-url-fopen-wrapper 參數來配置 PHP。
Windows 版本的 PHP 4.3 版之前不支援以下函數的遠端存取: include, include_once, require, require_once 以及GD and Image 函數中的 imagecreatefromXXX 函數。
例如,可以用以下範例來開啟遠程 網頁伺服器上的檔案,解析需要的輸出資料,然後將這些資料用在資料庫的檢索中,或者簡單地以和自己網站其它頁面相同的風格輸出其內容。
Example #1 擷取遠程檔案的標題
<?php $file = fopen ("/", "r"); if (!$file) { echo "<p>Unable to open remote file.\n"; exit; } while (!feof ($file)) { $line = fgets ($file, 1024); /* This only works if the title and its tags are on one line */ if (eregi ("<title>(.*)</title>", $line, $out)) { $title = $out[1]; break; } } fclose($file);?>
如果有合法的存取權限,以一個使用者的身份和某 FTP 伺服器建立了連結,還可以向該 FTP 伺服器端的檔案進行寫操作。僅能用該方法來建立新的檔案;如果嘗試覆蓋已經存在的檔案, fopen() 函數的調用將會失敗。
要以“anonymous”以外的使用者名稱串連伺服器,需要指明使用者名稱(可能還有密碼),例如“ftp://user:password@ftp.example.com/path/to/file”(也可以在通過需要 Basic 認證的 HTTP 協議訪問遠程檔案時使用相同的文法)。
Example #2 將資料儲存到遠程伺服器
<?php $file = fopen ("ftp://ftp.example.com/incoming/outputfile", "w"); if (!$file) { echo "<p>Unable to open remote file for writing.\n"; exit; } /* Write the data here. */ fwrite ($file, $_SERVER['HTTP_USER_AGENT'] . "\n"); fclose ($file);?>
注意:
或許可以從以上範例中得到啟發,用該技術來儲存遠程記錄檔。但是正如以上提到的,在用 fopen() 方式開啟的 URL 中,僅能對新檔案進行寫操作。如果遠程檔案已經存在則 fopen() 函數的操作將會失敗。要做類似於分布式日誌的事,可以參考 syslog() 函數。