1.安装ssh扩展,在扩展连接下载对应版本的扩展放到php/ext/下,而后更改php.ini,输出phpinfo(),能看到就表示成功了php
2.控制器代码(框架用的CI)框架
sftp类代码:ssh
<?php /** * Created by PhpStorm. * User: Administrator * Date: 2019/8/22 * Time: 16:00 */ class Sftp { private $connection; private $sftp; public function __construct($params) { $host = $params['host'];//地址 $port = $params['port'];//端口 $this->connection = ssh2_connect($host,$port); if (! $this->connection) throw new Exception("$host 链接 $port 端口失败"); } /** * 登陆 * @param string $login_type 登陆类型 * @param string $username 用户名 * @param string $password 密码 * @param string $pub_key 公钥 * @param string $pri_key 私钥 * @throws Exception] */ public function login($login_type,$username, $password = null,$pub_key = null,$pri_key = null) { switch ($login_type) { case 'username': //经过用户名密码登陆 $login_result = ssh2_auth_password($this->connection, $username, $password); break; case 'pub_key': //公钥私钥登陆 $login_result = ssh2_auth_pubkey_file($this->connection,$username,$pub_key,$pri_key); break; } if (! $login_result) throw new Exception("身份验证失败"); $this->sftp = ssh2_sftp($this->connection); if (! $this->sftp) throw new Exception("初始化sftp失败"); return true; } /** * 上传文件 * @param string $local_file 本地文件 * @param string $remote_file 远程文件 * @throws Exception */ public function upload_file($local_file, $remote_file) { $is_true = ssh2_scp_send($this->connection, $local_file, $remote_file, 0777); return $is_true; } /** * 下载文件 * @param $local_file * @param $remote_file */ public function down_file ($local_file, $remote_file) { ssh2_scp_recv($this->connection, $remote_file, $local_file); } /** * 判断文件夹是否存在 * @param string $dir 目录名称 * @return bool */ public function dir_exits ($dir) { return file_exists("ssh2.sftp://$this->sftp".$dir); } /** * 建立目录 * @param string $path 例子 '/home/username/newdir' * @param int $auth 默认 0777的权限 */ public function ssh2_sftp_mchkdir($path,$auth = 0777) //使用建立目录循环 { $end = ssh2_sftp_mkdir($this->sftp, $path,$auth,true); if ($end !== true) throw new Exception('文件夹建立失败'); } /** * 目录重命名 * @param string $dir 例子:'/home/username/newnamedir' * $dir 示例:/var/file/image * @return bool */ public function rename ($old_dir,$new_dir) { $is_true = ssh2_sftp_rename($this->sftp,$old_dir,$new_dir); return $is_true; } /** * 删除文件 * @param string $dir 例子:'/home/username/dirname/filename' * $dir 示例:/var/file/image/404NotFound.png * @return bool */ public function del_file ($dir) { $is_true = ssh2_sftp_unlink($this->sftp,$dir); return $is_true; } /** * 获取文件夹下的文件 * @param string $remote_file 文件路径 例:/var/file/image * @return array */ public function scan_file_system($remote_file) { $sftp = $this->sftp; $dir = "ssh2.sftp://$sftp$remote_file"; $tempArray = array(); $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); return $tempArray; } }
参考连接:https://www.php.net/manual/zh...this