最近開發一個與銀行合作的項目,需要上傳與下載文件。對文件保密有一定要求,所以用了SFTP。但實際開發中,遇到了很多問題,網上找的教程與案例都不能用,也是千遍一律 的,復制來,復制去的。最后在不斷的調試后終于實現了PHP的文件上傳與下載?,F記錄下來,僅供參考。
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手冊上找到了
會報錯,說明這個地址是錯的。最后檢查出上傳,下載地址不需要加上前面的
直接用SFTP文件路徑。
上傳使用的函數也不能用 前面 提到的 copy ,file_get_content ,curl
需要用
以上就是PHP+sftp 實現文件的上傳與下載 的詳細內容,更多請關注 其它相關文章!
鄭重聲明:本文版權歸原作者所有,轉載文章僅為傳播更多信息之目的,如作者信息標記有誤,請第一時間聯系我們修改或刪除,多謝。
新聞熱點
疑難解答