php实现ftp下载
使用PHP内置FTP函数实现下载
PHP提供了内置的FTP函数库,可以方便地实现FTP文件下载功能。以下是一个完整的实现示例:
$ftp_server = "ftp.example.com";
$ftp_username = "username";
$ftp_password = "password";
$remote_file = "/path/to/remote/file.txt";
$local_file = "localfile.txt";
$conn_id = ftp_connect($ftp_server) or die("无法连接到 $ftp_server");
if (@ftp_login($conn_id, $ftp_username, $ftp_password)) {
ftp_pasv($conn_id, true); // 启用被动模式
if (ftp_get($conn_id, $local_file, $remote_file, FTP_BINARY)) {
echo "文件下载成功\n";
} else {
echo "文件下载失败\n";
}
ftp_close($conn_id);
} else {
echo "登录失败\n";
}
使用cURL库实现FTP下载
cURL提供了更灵活的FTP操作方式,支持更多协议和选项:
$remote_file = "ftp://username:password@ftp.example.com/path/to/file.txt";
$local_file = "localfile.txt";
$fp = fopen($local_file, 'w');
$ch = curl_init($remote_file);
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_FTP_USE_EPSV, true); // 使用扩展被动模式
if (curl_exec($ch)) {
echo "文件下载成功\n";
} else {
echo "错误: " . curl_error($ch) . "\n";
}
curl_close($ch);
fclose($fp);
处理大文件下载
对于大文件下载,可以使用流式处理避免内存问题:
$ftp_server = "ftp.example.com";
$ftp_username = "username";
$ftp_password = "password";
$remote_file = "/large/file.zip";
$local_file = "localfile.zip";
$conn_id = ftp_connect($ftp_server);
ftp_login($conn_id, $ftp_username, $ftp_password);
ftp_pasv($conn_id, true);
$handle = fopen($local_file, 'w');
ftp_fget($conn_id, $handle, $remote_file, FTP_BINARY, 0);
fclose($handle);
ftp_close($conn_id);
错误处理和日志记录
在实际应用中应添加适当的错误处理和日志记录:
function downloadFromFTP($server, $user, $pass, $remote, $local) {
try {
$conn = ftp_connect($server);
if (!$conn) throw new Exception("连接失败");
if (!ftp_login($conn, $user, $pass)) {
throw new Exception("登录失败");
}
ftp_pasv($conn, true);
if (!ftp_get($conn, $local, $remote, FTP_BINARY)) {
throw new Exception("下载失败");
}
ftp_close($conn);
return true;
} catch (Exception $e) {
error_log("FTP错误: " . $e->getMessage());
if (isset($conn)) ftp_close($conn);
return false;
}
}
安全注意事项
使用FTP协议时应注意以下几点:

- 避免在代码中硬编码凭据
- 考虑使用SFTP/FTPS等更安全的协议
- 验证下载文件的完整性和安全性
- 设置适当的文件权限和目录限制






