使用SFTP上传文件

时间:2012-03-05 19:00:23

标签: php sftp

我已成功通过ftp上传文件,但我现在需要通过SFTP完成。我可以成功连接到远程服务器,创建文件并写入,但我无法将现有文件从本地服务器上传到远程服务器。 ftp_put是否没有使用sftp连接触发?

我的代码用于编写文件:

//Send file via sftp to server

$strServer = "*****";
$strServerPort = "****";
$strServerUsername = "*****";
$strServerPassword = "*****";
$csv_filename = "Test_File.csv";

//connect to server
$resConnection = ssh2_connect($strServer, $strServerPort);

if(ssh2_auth_password($resConnection, $strServerUsername, $strServerPassword)){
    //Initialize SFTP subsystem

    echo "connected";
    $resSFTP = ssh2_sftp($resConnection);    

    $resFile = fopen("ssh2.sftp://{$resSFTP}/".$csv_filename, 'w');
    fwrite($resFile, "Testing");
    fclose($resFile);                   

}else{
    echo "Unable to authenticate on server";
}

有没有人在抓取本地文件并通过sftp上面的方法上传?一个例子将不胜感激。

由于

5 个答案:

答案 0 :(得分:43)

使用上述方法(涉及sftp),您可以使用stream_copy_to_stream

$resFile = fopen("ssh2.sftp://{$resSFTP}/".$csv_filename, 'w');
$srcFile = fopen("/home/myusername/".$csv_filename, 'r');
$writtenBytes = stream_copy_to_stream($srcFile, $resFile);
fclose($resFile);
fclose($srcFile);

您也可以尝试使用ssh2_scp_send

答案 1 :(得分:23)

就个人而言,我更喜欢避免使用PECL SSH2扩展。我首选的方法是phpseclib, a pure PHP SFTP implementation。例如

<?php
include('Net/SFTP.php');

$sftp = new Net_SFTP('www.domain.tld');
if (!$sftp->login('username', 'password')) {
    exit('Login Failed');
}

$sftp->put('remote.ext', 'local.ext', NET_SFTP_LOCAL_FILE);
?>

我喜欢phpseclib超越PECL扩展的一个重要原因是它是可移植的。也许PECL扩展适用于一个版本的Linux但不适用于另一个版本。在共享主机上,它几乎从不起作用,因为它几乎没有安装过。

令人惊讶的是,phpseclib也是faster。如果您需要确认上传的文件,您可以使用phpseclib的内置日志记录作为证据。

答案 2 :(得分:11)

对我来说这很有效:

$connection = ssh2_connect($server, $serverPort);

if(ssh2_auth_password($connection, $serverUser, $serverPassword)){
    echo "connected\n";
    ssh2_scp_send($connection, "/path/to/local/".$file, "/path/to/remote/".$file);
    echo "done\n";
} else {
    echo "connection failed\n";
}

我不得不首先安装libssh2-php:

sudo apt-get install libssh2-php

答案 3 :(得分:4)

对于 phpseclib的简单文档,纯PHP SFTP实现

参考以下链接:

Uploading files over SFTP using PHP

文件夹结构:

Main Folder->
    my-files(Contain File Which Transfer To Remote Server)
    phpseclib0.3.0
    sftp.php

答案 4 :(得分:1)

共享更多输入,发现当将文件从Linux(64位)复制到Windows(32位)时,ssh2_scp_send没有正确复制(字节不同),sftp例程工作正常。当使用带有stfp的Windows时,如果在Windows上使用Cygwin进行SSH,则需要将C:\ to \ path的路径作为ssh2.sftp:// {$ resSFTP} / cygdrive / c /添加到/ path

相关问题