PHP SFTP簡單上傳下載實現
阿新 • • 發佈:2018-11-02
1 下載ssh2檔案
下載地址 http://windows.php.net/downloads/pecl/releases/ssh2/0.12/
根據自己PHP的版本去下載,其中ts表示執行緒安全,nts表示不安全。
(可以使用phpinfo()檢視需要哪一個,Thread Safety項是enabled表示執行緒安全)
2 安裝ssh2
解壓php_ssh2.zip
- 將 php_ssh.dll、php_ssh2.pdb 放到你的 php 擴充套件目錄下 php/ext/ 下。
- 將libssh2.dll 複製到 c:/windows/system32 和 c:/windows/syswow64 各一份
- php.ini中加入 extension=php_ssh2.dllphp.ini中加入 extension=php_ssh2.dll
- 重啟PHP
3 sftp的連線上傳下載
/** * Sftp上傳下載檔案 * */ namespace Common\ORG\Util; class Sftp { // 初始配置為NULL private $config = NULL; // 連線為NULL private $conn = NULL; // 初始化 public function __construct($config) { $this->config = $config; $this->connect(); } public function connect() { $this->conn = ssh2_connect($this->config['host'], $this->config['port']); //資源 if( ssh2_auth_password($this->conn, $this->config['username'], $this->config['password'])) { }else{ echo "無法在伺服器進行身份驗證"; } } // 傳輸資料 傳輸層協議,獲得資料 public function downftp($remote, $local) { $ressftp = ssh2_sftp($this->conn); return copy("ssh2.sftp://{$ressftp}".$remote, $local); } // 傳輸資料 傳輸層協議,寫入ftp伺服器資料 public function upftp( $local,$remote, $file_mode = 0777) { $ressftp = ssh2_sftp($this->conn); return copy($local,"ssh2.sftp://{$ressftp}".$remote); } }
4 例項
$config = array( 'host' =>'', //伺服器 'port' => '22', //埠 'username' =>'', //使用者名稱 'password' =>'', //密碼 ); $ftp = new Sftp($config); $localpath="D:/234.txt"; //原始檔地址 $serverpath='/234.txt'; //上傳sftp地址 $st = $ftp->upftp($localpath,$serverpath); //上傳指定檔案 if($st == true){ echo "success"; }else{ echo "fail"; }
地址路徑區分大小寫,sftp地址要寫完整!!!!!!