php 操作sftp,php sftp操作文件

1、需求:

a、需要将代码生成的文件上传到指定的sftp服务器的文件夹中

b、将sftp服务器的中文件清除并上传新的文件

2、准备:

a、php环境需要安装ssh扩展

b、mac安装php的ssh扩展命令:pecl install ssh2-1.1.2,安装完成扩展后将extension=ssh2.so加到php.ini文件中

7799126eb98f

image.png

3、代码:

namespace App\Sftp;

class Sftp {

// 连接为NULL

private $conn = NULL;

//sftp resource

private $ressftp = NULL;

// 初始化,$config是sftp的连接信息

public function __construct($config)

{

if( !$this->ressftp ){

$this->conn = ssh2_connect($config->host, $config->port);

if (ssh2_auth_password($this->conn, $config->username, $config->password)) {

$this->ressftp = ssh2_sftp($this->conn);//启动引力传动系统

} else {

throw new \Exception("用户名或密码错误");

}

}

return $this->ressftp;

}

/**

* 判段远程目录是否存在

* @param $dir /远程目录

* @return bool

*/

public function ssh2_dir_exits($dir){

return file_exists("ssh2.sftp://" . intval($this->ressftp) .$dir);

}

/**

* 下载文件

* @param $remote /远程文件地址

* @param $local /下载到本地的地址

* @return bool

*/

public function downSftp($remote, $local)

{

return copy("ssh2.sftp://" . intval($this->ressftp).$remote, $local);

}

/**

* 文件上传

* @param $local /本地文件地址

* @param $remote /上传后的文件地址

* @param int $file_mode

* @return bool

*/

public function upSftp($local,$remote, $file_mode = 0777)

{

return copy($local, "ssh2.sftp://" . intval($this->ressftp) . $remote);

}

/**

* 删除远程目录中文件

* @param $file

* @return bool

*/

public function deleteSftp($file)

{

return ssh2_sftp_unlink($this->ressftp, $file);

}

/**

* 遍历远程目录

* @param $remotePath

* @return array

*/

public function fileList($remotePath)

{

$fileArr = scandir('ssh2.sftp://' . intval($this->ressftp) . $remotePath);

foreach ($fileArr as $k => $v) {

if ($v == '.' || $v == '..') {

unset($fileArr[$k]);

}

}

return $fileArr;

}

/**

* 创建远程目录中文件夹

* @param $file

* @return bool

*/

public function ssh2_sftp_mkdir($dir)

{

return ssh2_sftp_mkdir($this->ressftp, $dir);

}

}

3、注意点:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值