PHP+sftp 实现文件的上传与下载

零到壹度
零到壹度 原创
2023-03-23 16:06:01 4113浏览

本篇文章给大家分享的内容是PHP+sftp实现的文件上传与下载,有着一定的参考价值,有需要的朋友可以参考一下

最近开发一个与银行合作的项目,需要上传与下载文件。对文件保密有一定要求,所以用了SFTP。但实际开发中,遇到了很多问题,网上找的教程与案例都不能用,也是千遍一律 的,复制来,复制去的。最后在不断的调试后终于实现了PHP的文件上传与下载。现记录下来,仅供参考。

1.检查PHP版本,下载对应ssh2 扩展 https://windows.php.net/downloads/pecl/releases/ssh2/ ,具体安装,麻烦网上搜索一下。phpinfo()检查是否安装好。安装成功后,可以看到ssh2.

2. 网上提供的上传下截方法 (相信你肯定看到过)

<·?·php
//php环境中必须有ssh
·$strServer = "服务器ip";//服务器ip
·$strServerPort = "22";//端口号
·$strServerUsername = "***";//用户名
·$strServerPassword = "***";//密码
·//connect to server
·$resConnection = ssh2_connect($strServer, $strServerPort);
·if(ssh2_auth_password($resConnection, $strServerUsername, $strServerPassword)){
·//初始化 SFTP
·$resSFTP = ssh2_sftp($resConnection);
·echo $resSFTP;
·//下载文件
·//1
·$filename = 'D:\down'.time().'.txt';
·$opts = array(
·'http'=>array(
·'method'=>"GET",
·'timeout'=>60,
·)
·);
·$context = stream_context_create($opts);
·$strData = ·file_get_contents("ssh2.sftp://{$resSFTP}/var/testfile/abc.txt", false, $context);
·file_put_contents($filename, $strData);
·//2 也可以用copy()
·//if(!copy("ssh2.sftp://{$resSFTP}/dfr508/WUN/ikea-logo.jpg", $filename)) {
·// echo 'download failed';
·//}
·//--------------------------------------------------------------------------------------------------------------
·//上传文件
·//1
·//file_put_contents("ssh2.sftp://{$resSFTP}/var/testfile/456.txt", 'D:/ab.txt');
·//2也可以用copy()
·if(!copy("d:/ab.txt", "ssh2.sftp://{$resSFTP}/var/testfile/up".time().".txt")) {
·echo 'upload failed';
·}
·} else {
·echo "无法在服务器进行身份验证";
·}
·?·>

但是我自己按照网上的教程,怎么也实现 不了,最后只好一步步排查原因。

         $strServer = "";//服务器ip         
         $strServerPort = "";//端口号     
 $strServerUsername = "";//用户名     
 $strServerPassword = "";//密码    
 //1连接服务器      
     $resConnection = ssh2_connect($strServer, $strServerPort);        
     //2验证连        
     if(ssh2_auth_password($resConnection, $strServerUsername, $strServerPassword)){       
          //3初始化 SFTP            
          $resSFTP = ssh2_sftp($resConnection);

首先前面3步是没有问题的

用copy ,file_get_content ,curl 方法实现上传下载都 报502错误 。检查了路径等问题,也没问题 ,但就是不能成功。

后面推断sftp服务器上的文件地址不能访问。

"ssh2.sftp://{$resSFTP}/var/testfile/abc.txt"

现在只有找到真正可用的地址才行,查看了很多资料,最后在PHP手册上找到了

ssh2_sftp_realpath 检查文件真实路径,最后返回连接上SFTP后访问文件的地址。传入"ssh2.sftp://{$resSFTP}/var/testfile/abc.txt"

会报错,说明这个地址是错的。最后检查出上传,下载地址不需要加上前面的

sh2.sftp://{$resSFTP}

直接用SFTP文件路径。

上传使用的函数也不能用 前面 提到的 copy ,file_get_content ,curl

需要用

ssh2_scp_send 上传

ssh2_scp_recv 下载

以上就是PHP+sftp 实现文件的上传与下载 的详细内容,更多请关注php中文网其它相关文章!

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。