PHP-sftp文件上传
生活随笔
收集整理的這篇文章主要介紹了
PHP-sftp文件上传
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
個人博客地址https://xgs888.top/post/view?id=57
PHP的sftp文件上傳;在框架thinkphp5中使用;
主要用到的sftp函數(shù)如下;
ssh2_connect(host,port) 鏈接信息
ssh2_auth_password($con,username,password)登錄驗證
copy();//服務(wù)器之間的文件復(fù)制;
要求如下
需要的文件字段信息見附件內(nèi)容,注意最后一列帶年月日時分秒格式;
上傳前,需要先判斷相應(yīng)目錄下是否有上一天日期文件夾,若無,則創(chuàng)建,若有,則直接上傳至相應(yīng)文件夾下,如附件所示
thinkphp5中提供了一個非composer安裝的第三方類庫目錄extend
在extend目錄下創(chuàng)建一個sftp目錄創(chuàng)建sftp.php的類
namespace?sftp; class?Sftp {//?初始配置為NULLprivate?$config?=?NULL;//?連接為NULLprivate?$conn?=?NULL;//sftp?resource?private?$ressftp?=?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'])){$this->ressftp?=?ssh2_sftp($this->conn);}else{?echo?"用戶名或密碼錯誤";}}//?下載文件public?function?downftp($remote,?$local){?return?copy("ssh2.sftp://{$ressftp}".$remote,?$local);}//?文件上傳public?function?upftp(?$local,$remote,?$file_mode?=?0777){?return?copy($local,"ssh2.sftp://{$this->ressftp}".$remote);?}//創(chuàng)建目錄public?function?ssh2_sftp_mchkdir($path)??//使用創(chuàng)建目錄循環(huán){ssh2_sftp_mkdir($this->ressftp,?$path,0777);}//判段目錄是否存在public?function?ssh2_dir_exits($dir){return?file_exists("ssh2.sftp://{$this->ressftp}".$dir);}}下面在控制器里面調(diào)用
namespace?app\index\controller;use?think\Controller; use?\sftp\sftp; class?Index?extends?Controller {public?function?index(){ini_set('max_execution_time','0');//設(shè)置永不超時$time?=?date('ymd',time()-24*3600);//上一天的日期$name?=?"mac".$time;$data?=?db('table')->where("add_date='2017-10-09'")->select();//查詢數(shù)據(jù)$fp?=?fopen("$name.csv","a");?//打開csv文件,如果不存在則創(chuàng)建$datastr?=?'id,sitecode,devmac,stamac,add_date,up_time'."\r\n";foreach?($data?as?$key?=>?$value)?{#?code...$datastr?=?$datastr.$value['id'].$value['sitecode'].','.$value['devmac'].','.$value['stamac'].','.$value['add_date'].','.$value['up_time']."\r\n";}//iconv('GB2312','UTF-8//IGNORE',$datastr)fwrite($fp,$datastr);?//寫入數(shù)據(jù)講gbk轉(zhuǎn)成utf8fclose($fp);?//關(guān)閉文件句柄echo?"生成成功";$config?=?array('host'=>'127.0.0.1','username'=>'root','password'=>'root','port'=>'22');$sftp?=?new?sftp($config);$re?=?$sftp->ssh2_dir_exits("/test/$time");if($re){//如果目錄存在直接上傳$sftp->upftp("$name.csv",'/test/'.$time.'/'.$name.'.csv');}else{$sftp->ssh2_sftp_mchkdir('/test/'.$time);$sftp->upftp("$name.csv",'/test/'.$time.'/'.$name.'.csv');}}}轉(zhuǎn)載于:https://blog.51cto.com/11760810/2044534
總結(jié)
以上是生活随笔為你收集整理的PHP-sftp文件上传的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: NAT原理与配置
- 下一篇: 实现在CentOS7环境下搭建个人git