【问题标题】:Upload file from local to SFTP via PHP SSH2通过 PHP SSH2 将文件从本地上传到 SFTP
【发布时间】:2023-05-31 16:23:02
【问题描述】:

我正在尝试通过 PHP 将本地文件从我的 Mac 上传到 SFTP。我的代码:

$connection = ssh2_connect($server, $port);
if (ssh2_auth_password($connection, $username, $passwd)) {
$sftp = ssh2_sftp($connection);
echo "Connection successful, uploading file now..."."\n";
$file = '/Users/petenaylor/Desktop/diamondexclusive.mp4';
$contents = file_get_contents($file);
file_put_contents("ssh2.sftp://{$sftp}/{$file}", $contents);
} 
else {
    echo "Unable to authenticate with server"."n";
}

它按应有的方式连接,我检查了本地文件位置是否正确,但我收到的错误消息是:

警告:file_get_contents(/Users/petenaylor/Desktop/diamonexclusive.mp4):无法打开流:第 39 行的 /home/test.php 中没有此类文件或目录

警告:file_put_contents(): Unable to open ssh2.sftp://Resource id #3//Users/petenaylor/Desktop/diamondexclusive.mp4 on remote host in /home/test.php on line 40

警告:file_put_contents(ssh2.sftp://Resource id #3//Users/petenaylor/Desktop/diamonexclusive.mp4):打开流失败:/home/test.php 第 40 行的操作失败

我的 Filezilla 日志文件:

Command:    put "/Users/petenaylor/Desktop/diamondexclusive.mp4" "diamondexclusive.mp4"
Status:         local:/Users/petenaylor/Desktop/diamondexclusive.mp4 => remote:/home/myfarewellnote/web/diamondexclusive.mp4
Trace:          FileTransferParseResponse(0)
Trace:          CSftpControlSocket::ResetOperation(0)
Trace:          CControlSocket::ResetOperation(0)
Status:         File transfer successful, transferred 12,661,295 bytes in 111 seconds
Status:         Retrieving directory listing of "/home/myfarewellnote/web"...
Trace:          CSftpControlSocket::ParseSubcommandResult(0)
Trace:          CSftpControlSocket::ListSubcommandResult()
Trace:          CSftpControlSocket::SendNextCommand()
Trace:          CSftpControlSocket::ListSend()
Command:    ls
Status:         Listing directory /home/myfarewellnote/web
Trace:          CSftpControlSocket::ListParseResponse()
Trace:          CSftpControlSocket::ResetOperation(0)
Trace:          CControlSocket::ResetOperation(0)
Status:         Directory listing of "/home/myfarewellnote/web" successful

【问题讨论】:

  • 您能否使用独立(GUI 或命令行)SFTP 客户端将文件上传到/Users/petenaylor/Desktop/diamondexclusive.mp4?如果可以,请向我们展示它的日志文件。
  • 我可以通过 FileZilla 成功完成。我应该从那里提供日志文件吗?
  • 是的,请。详细日志文件。
  • 这个窗口很大。

标签: php ssh ftp sftp


【解决方案1】:

在 FileZilla 中,您将一个名为 diamondexclusive.mp4 的文件上传到当前远程工作目录 /home/myfarewellnote/web

因此完整的目标路径是/home/myfarewellnote/web/diamondexclusive.mp4

在 PHP 中,您将文件上传到 /Users/petenaylor/Desktop/diamondexclusive.mp4(实际上是本地源路径,与服务器无关)。

使用您在 FileZilla 中上传文件的相同路径:

file_put_contents("ssh2.sftp://{$sftp}/home/myfarewellnote/web/diamondexclusive.mp4", $contents);

【讨论】:

    最近更新 更多