phpファイルをsftpにアップロードするか、sftpからファイルをダウンロードします



Php Upload File Sftp



前回の記事では、WindowsでfreeSSHdを使用してローカルのsftpサーバーを構築する方法について説明しました。 クリックして表示
これは、phpを使用してsftpからファイルをダウンロードおよびアップロードするための別の書き込みです。

sftpクラス

class sftpData{ private $config private $connect = NULL private $resource = NULL public function __construct($config) { $this->config = $config // Connect sftp ssh2_connect (host, port) $this->connect = ssh2_connect($this->config['host'], $this->config['port']) // Verify username and password ssh2_auth_password ($ connect, username, password) if( ssh2_auth_password($this->connect, $this->config['username'], $this->config['password'])) { $this->resource = ssh2_sftp($this->connect) }else{ echo 'Login failed, check username / password' } } /** * download file * @param $ remote, remote file address * @param $ local, local file address * @return bool */ public function downloadSftp($remote, $local) { return copy('ssh2.sftp://'.$this->resource.$remote, $local) } /** * File Upload * @param $ local, local file address * @param $ remote, remote file address * @return bool */ public function uploadSftp( $local,$remote) { // Get the directory of the uploaded file $dir = dirname($remote) // Determine whether the uploaded directory exists $is_dir = $this->sftp_is_dir($dir) if(!$is_dir){ // The directory does not exist, create a directory $this->sftp_mkdir($dir) } return copy($local,'ssh2.sftp://'.$this->resource.$remote) } /** * Create sftp directory * @param $dir */ public function sftp_mkdir($dir) // Use create directory loop { ssh2_sftp_mkdir($this->resource, $dir,0777,true) } /** * Check if the directory exists * @param $dir * @return bool */ public function sftp_is_dir($dir){ return file_exists('ssh2.sftp://'.$this->resource.$dir) } } ?>

ファイルデモをアップロード

// sftp connection configuration $config = [ 'host'=>'127.0.0.1', 'port'=>'23', 'username'=>'aShin', 'password'=>'aShin', ] $sftp = new sftpData($config) // The file path to be uploaded locally $localPath='C:/Users/aShin/Desktop/333.txt' // The sftp path to upload $remotePath='/aShin/333.txt' //upload files $res = $sftp->uploadSftp($localPath,$remotePath) if($res){ echo 'upload success' }else{ echo 'upload fail' } ?>

ファイルデモをダウンロード

// sftp connection configuration $config = [ 'host'=>'127.0.0.1', 'port'=>'23', 'username'=>'aShin', 'password'=>'aShin', ] $sftp = new sftpData($config) // The file path to be saved $localPath='C:/Users/aShin/Desktop/11.txt' // The file path to download $remotePath='/11.txt' $res = $sftp->downloadSftp($remotePath,$localPath) if($res){ echo 'download success' }else{ echo 'download fail' } ?>