PHP-sftp 파일 업로드

개인 블 로그 주소https://xgs888.top/post/view?id=57
PHP 의 sftp 파일 업로드;프레임 워 크 thinkpphp 5 에서 사용 하기;
주로 사용 되 는 sftp 함 수 는 다음 과 같 습 니 다.
ssh2_connect(host,port)링크 정보
ssh2_auth_비밀번호($con,username,password)로그 인 인증
copy();//서버 간 파일 복사;
요 구 는 아래 와 같다
필요 한 파일 필드 정 보 는 첨부 파일 내용 을 볼 수 있 습 니 다.마지막 열 에 있 는 년 월 일 분 초 형식 에 주의 하 십시오.
업로드 하기 전에 해당 디 렉 터 리 에 전날 날짜 폴 더 가 있 는 지 판단 하고 없 으 면 만 들 고 있 으 면 해당 폴 더 에 직접 업로드 해 야 합 니 다.첨부 파일 과 같 습 니 다.
thinkpp 5 에서 비 composer 가 설치 한 제3자 라 이브 러 리 디 렉 터 리 extend 를 제공 합 니 다.
extend 디 렉 터 리 아래 sftp 디 렉 터 리 를 만 들 고 sftp.php 클래스 를 만 듭 니 다.
namespace sftp;
class Sftp
{
  
	 //      NULL
	 private $config = NULL;
	 //    NULL
	 private $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); 
	  
	 }
	 //    
	 public function ssh2_sftp_mchkdir($path)  //        
	{
		ssh2_sftp_mkdir($this->ressftp, $path,0777);
	}
	//        
	public function ssh2_dir_exits($dir){
		return file_exists("ssh2.sftp://{$this->ressftp}".$dir);
	}
  
}

다음은 컨트롤 러 에서 호출 합 니 다.
namespace app\index\controller;

use think\Controller;
use \sftp\sftp;
class Index extends Controller
{
    public function index()
    {
    	ini_set('max_execution_time','0');//      
    	$time = date('ymd',time()-24*3600);//      

    	$name = "mac".$time;
         $data = db('table')->where("add_date='2017-10-09'")->select();//    
         $fp = fopen("$name.csv","a"); //  csv  ,        
		 $datastr = 'id,sitecode,devmac,stamac,add_date,up_time'."\r
";  foreach ($data as $key => $value) {   # code...   $datastr = $datastr.$value['id'].$value['sitecode'].','.$value['devmac'].   ','.$value['stamac'].','.$value['add_date'].','.$value['up_time']."\r
";  }  //iconv('GB2312','UTF-8//IGNORE',$datastr)  fwrite($fp,$datastr); // gbk utf8  fclose($fp); //  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'); }     }    }

좋은 웹페이지 즐겨찾기