通过PHP SSH2

时间:2016-11-03 13:25:58

标签: php ssh ftp sftp

我正在尝试通过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/diamondexclusive.mp4):无法打开流:第39行/home/test.php中没有此类文件或目录

警告:file_put_contents():无法在第40行的/home/test.php中的远程主机上打开ssh2.sftp://资源ID#3 // Users / petenaylor / Desktop / diamondexclusive.mp4

警告:file_put_contents(ssh2.sftp://资源ID#3 // Users / petenaylor / Desktop / diamondexclusive.mp4):无法打开流:第40行/home/test.php中的操作失败

来自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

1 个答案:

答案 0 :(得分: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);
相关问题