我已成功通过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";
}
Run Code Online (Sandbox Code Playgroud)
有没有人在抓取本地文件并通过sftp上面的方法上传?一个例子将不胜感激.
谢谢
dev*_*ler 45
使用上面的方法(涉及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);
Run Code Online (Sandbox Code Playgroud)
您也可以尝试使用ssh2_scp_send
neu*_*ert 25
就个人而言,我更喜欢避免使用PECL SSH2扩展.我首选的方法涉及phpseclib,一种纯PHP SFTP实现.例如.
<?php
require __DIR__ . '/vendor/autoload.php';
use phpseclib\Net\SFTP;
$sftp = new SFTP('www.domain.tld');
if (!$sftp->login('username', 'password')) {
exit('Login Failed');
}
$sftp->put('remote.ext', 'local.ext', SFTP::SOURCE_LOCAL_FILE);
?>
Run Code Online (Sandbox Code Playgroud)
关于PECL扩展,我喜欢phpseclib的一个重要原因是它是可移植的.也许PECL扩展适用于一个版本的Linux但不适用于另一个版本.在共享主机上,它几乎从不起作用,因为它几乎没有安装过.
令人惊讶的是,phpseclib也更快.如果您需要确认上传的文件,您可以使用phpseclib的内置日志记录作为证据.
小智 12
对我来说,这工作:
$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";
}
Run Code Online (Sandbox Code Playgroud)
我不得不首先安装libssh2-php,但是:
sudo apt-get install libssh2-php
Run Code Online (Sandbox Code Playgroud)