当前位置: 首页 > 后端技术 > PHP

PHP使用sftp上传文件

时间:2023-03-30 05:51:10 PHP

1、安装ssh扩展,从扩展链接下载对应版本的扩展放到php/ext/下,然后更改php.ini,输出phpinfo(),如果能看到就说明成功2、Controller代码(框架的CI)sftp类代码:connection=ssh2_connect($host,$port);if(!$this->connection)thrownewException("无法将$port连接到$host");}/***Login*@paramstring$login_type登录类型*@paramstring$usernameusername*@paramstring$passwordpassword*@paramstring$pub_key公钥*@paramstring$pri_key私钥*@throwsException]*/publicfunctionlogin($login_type,$username,$password=null,$pub_key=null,$pri_key=null){switch($login_type){case'username'://使用用户名和密码登录$login_result=ssh2_auth_password($this->connecti上,$用户名,$密码);休息;case'pub_key'://公钥私钥登录$login_result=ssh2_auth_pubkey_file($this->connection,$username,$pub_key,$pri_key);休息;}if(!$login_result)thrownewException("Authenticationfailed");$this->sftp=ssh2_sftp($this->connection);if(!$this->sftp)thrownewException("无法初始化sftp");返回真;}/***上传文件*@paramstring$local_file本地文件*@paramstring$remote_file远程文件*@throwsException*/publicfunctionupload_file($local_file,$remote_file){$is_true=ssh2_scp_send($this->connection,$local_file,$remote_file,0777);返回$is_true;}/***下载文件*@param$local_file*@param$remote_file*/publicfunctiondown_file($local_file,$remote_file){ssh2_scp_recv($this->connection,$remote_file,$local_file);}/***判断文件夹是否存在*@paramstring$dir目录名*@returnbool*/publicfunctiondir_exits($dir){returnfile_exists("ssh2.sftp://$this->sftp".$dir);}/***创建目录*@paramstring$pathexample'/home/username/newdir'*@paramint$authdefault0777权限*/publicfunctionssh2_sftp_mchkdir($path,$auth=0777)//用于创建目录循环{$end=ssh2_sftp_mkdir($this->sftp,$path,$auth,true);if($end!==true)thrownewException('文件夹创建失败');}/***目录重命名*@paramstring$dir示例:'/home/username/newnamedir'*$dir示例:/var/file/image*@returnbool*/publicfunctionrename($old_dir,$new_dir){$is_true=ssh2_sftp_rename($this->sftp,$old_dir,$new_dir);返回$is_true;}/***删除文件*@paramstring$dir示例:'/home/username/dirname/filename'*$dir示例:/var/file/image/404NotFound.png*@returnbool*/publicfunctiondel_file($目录){$is_true=ssh2_sftp_unlink($this->sftp,$dir);返回$is_true;}/***获取文件夹下的文件*@paramstring$remote_file文件路径示例:/var/file/image*@returnarray*/publicfunctionscan_file_system($remote_file){$sftp=$this->sftp;$dir="ssh2.sftp://$sftp$remote_file";$tempArray=数组();$handle=opendir($dir);//所有文件的列表while(false!==($file=readdir($handle))){if(substr("$file",0,1)!="."){if(is_dir($file)){//$tempArray[$file]=$this->scanFilesystem("$dir/$file");}else{$tempArray[]=$file;}}}closedir($handle);返回$tempArray;}}参考链接:https://www.php.net/manual/zh...