Php 使用SFTP上载文件
我已经成功地通过ftp上传了文件,但我现在需要通过SFTP进行上传。我可以成功连接到远程服务器,创建文件并写入,但无法将现有文件从本地服务器上载到远程服务器。ftp_put是否未使用sftp连接触发 我用于编写文件的代码:Php 使用SFTP上载文件,php,sftp,Php,Sftp,我已经成功地通过ftp上传了文件,但我现在需要通过SFTP进行上传。我可以成功连接到远程服务器,创建文件并写入,但无法将现有文件从本地服务器上载到远程服务器。ftp_put是否未使用sftp连接触发 我用于编写文件的代码: //Send file via sftp to server $strServer = "*****"; $strServerPort = "****"; $strServerUsername = "*****"; $strServerPassword = "*****";
//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通过上述方法上传?请举个例子,不胜感激
感谢使用上述方法(涉及sftp),您可以使用:
您也可以尝试亲自使用,我更喜欢避免使用PECL SSH2扩展。我更喜欢的方法包括。下面是phpseclib 2.0(需要编写器)的一个示例:
以下是phpseclib 1.0的相同示例:
<?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也是。如果您需要确认上传的文件,您可以使用phpseclib的内置日志作为证据。共享进一步的输入,发现ssh2\u scp\u send在将文件从Linux(64位)复制到Windows(32位)时没有正确复制(字节不同),sftp例程工作正常。在将Windows与stfp一起使用时,C:\to\path的路径需要放在ssh2.sftp://{$resSFTP}/cygdrive/C/to/path,如果Cygwin用于Windows框上的SSH。对于phpseclib的简单文档,这是一个纯PHP sftp实现 请参阅以下链接: 文件夹结构:
Main Folder->
my-files(Contain File Which Transfer To Remote Server)
phpseclib0.3.0
sftp.php
对我来说,这很有效:
$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
非常好,谢谢。我将为未来的项目添加书签!这太棒了,但别忘了禁用用户的open base dir。我正在使用上面的脚本上载一些csv文件,但我遇到了以下错误:Net\SSH2.php第3521行的最大执行时间超过了120秒,我怎么能超过它呢。你为什么称它为
resFile
?为什么是“res”?它代表什么?我猜结果@Black您在src中在哪里使用了$strServerPassword
?我看不到它在这里被使用。我得到的包libssh2 php不可用,所以请使用sudo apt get install php-ssh2
$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";
}
sudo apt-get install libssh2-php