You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用PHP的ftp_ssl_connect获取SFTP文件遇504错误,求解决

问题根源&解决方案
  • 核心问题:你搞混了协议!FileZilla显示sftp://,说明服务器用的是SFTP(SSH文件传输协议),但你用的ftp_ssl_connect是用来连**FTPS(FTP over SSL/TLS)**的,这俩完全不是一回事,协议不兼容自然报错。
  • 为啥ftp_connect能跑?大概率是目标服务器同时开了普通FTP服务,但你实际要连的是SFTP(不然FileZilla不会显示sftp://)。指定22端口没用,因为ftp_ssl_connect本质还是FTP协议,硬塞到SSH端口(22)上,服务器根本认不出你的FTP命令,返回504超时很正常。
  • 正确做法:PHP操作SFTP得用SSH扩展的函数,比如ssh2_connect+ssh2_sftp,示例代码大概是这样:
// 连接SSH服务器
$connection = ssh2_connect('你的服务器地址', 22);
ssh2_auth_password($connection, '用户名', '密码');

// 初始化SFTP
$sftp = ssh2_sftp($connection);

// 列出指定目录下的*add.zip文件
$dir = '/1668161919_DATA';
$files = scandir("ssh2.sftp://$sftp$dir");
$addZipFiles = array_filter($files, function($file) {
    return preg_match('/.*add\.zip$/', $file);
});

// 下载最新的文件
if (!empty($addZipFiles)) {
    // 按修改时间排序,取最新的
    usort($addZipFiles, function($a, $b) use ($sftp, $dir) {
        $aStat = ssh2_sftp_stat($sftp, "$dir/$a");
        $bStat = ssh2_sftp_stat($sftp, "$dir/$b");
        return $bStat['mtime'] - $aStat['mtime'];
    });
    $latestFile = reset($addZipFiles);
    ssh2_scp_recv($connection, "$dir/$latestFile", "本地保存路径/$latestFile");
}
  • 注意:如果你的PHP没装ssh2扩展,要么给PHP装这个扩展,要么用PHPSecLib这种纯PHP的SFTP库来实现。

内容的提问来源于stack exchange,提问作者PaulW32

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 00:25:30