以下是如何允許 fopen() 覆寫 FTP 站點上檔案的範例。如果未修改串流上下文,將會發生錯誤:「...failed to open stream: Remote file already exists and overwrite context option not specified...」(...無法開啟串流:遠端檔案已存在且未指定覆寫上下文選項...)。
<?php
// FTP 檔案的路徑,包含登入參數
$ftp_path = 'ftp://username:password@example.com/example.txt';
// 允許覆寫遠端 FTP 伺服器上的現有檔案
$stream_options = array('ftp' => array('overwrite' => true));
// 使用已定義的選項建立串流上下文資源
$stream_context = stream_context_create($stream_options);
// 開啟檔案以進行寫入並將其截斷為零長度
if ($fh = fopen($ftp_path, 'w', 0, $stream_context))
{
// 將內容寫入檔案
fputs($fh, 'example contents');
// 關閉檔案控制代碼
fclose($fh);
}
else
{
die('Could not open file.');
}
?>