是否曾需要從 URI 建立預設到特定目錄的 FTP 連線資源?以下是一個簡單的函式,它會接受像 ftp://username:password@subdomain.example.com/path1/path2/, 這樣的 URI,並返回一個 FTP 連線資源。
<?php
函式 getFtpConnection($uri)
{
// 將 FTP URI 拆分為:
// $match[0] = ftp://username:password@sld.domain.tld/path1/path2/
// $match[1] = ftp://
// $match[2] = 使用者名稱
// $match[3] = 密碼
// $match[4] = sld.domain.tld
// $match[5] = /path1/path2/
preg_match("/ftp:\/\/(.*?):(.*?)@(.*?)(\/.*)/i", $uri, $match);
// 建立連線
$conn = ftp_connect($match[1] . $match[4] . $match[5]);
// 登入
if (ftp_login($conn, $match[2], $match[3]))
{
// 切換目錄
ftp_chdir($conn, $match[5]);
// 返回資源
return $conn;
}
// 或返回 null
return null;
}
?>