php implement ftp and sftp upload and download files

PHP FTP, SFTP upload and download

When connecting to three parties, the interface is encrypted and then transferred by FTP or SFTP, and connected by PHP. So this article (based on TP3.2) was born. This article includes the following points:

  • base code
  • Instructions
  • Notes on compiling and installing PHP's SFTP extension library

Please indicate the  reprint—— [Xiao Yixi]

1. PHP's FTP and SFTP code, copy and use directly

Please refer to the official documents of FTP and SFTP: 
http://php.net/manual/en/book.ftp.php

http://php.net/manual-lookup.php?pattern=SFTP&scope=quickref

The following is the core code of this article, copy and use directly:

1、FTP

  • Create a new php file in the TP3.2 storage class file directory (Common/Org/): ftp.class.php
<?php
/******************************************** 
* MODULE:FTP类 
*******************************************/
class ftp 
{ 
  public $off;             // 返回操作状态(成功/失败) 
  public $conn_id;           // FTP连接 

  /** 
  * 方法:FTP连接 
  * @FTP_HOST -- FTP主机 
  * @FTP_PORT -- 端口 
  * @FTP_USER -- 用户名 
  * @FTP_PASS -- 密码 
  */
  function __construct($FTP_HOST,$FTP_PORT,$FTP_USER,$FTP_PASS) 
  { 
    $this->conn_id = @ftp_connect($FTP_HOST,$FTP_PORT) or die("FTP服务器连接失败"); 
    @ftp_login($this->conn_id,$FTP_USER,$FTP_PASS) or die("FTP服务器登陆失败"); 
    @ftp_pasv($this->conn_id,1); // 打开被动模拟 
  } 

  /** 
  * 方法:上传文件 
  * @path  -- 本地路径 
  * @newpath -- 上传路径 
  * @type  -- 若目标目录不存在则新建 
  */
  function up_file($path,$newpath,$type=true) 
  { 
    if($type) $this->dir_mkdirs($newpath); 
    $this->off = @ftp_put($this->conn_id,$newpath,$path,FTP_BINARY); 
    if(!$this->off) echo "文件上传失败,请检查权限及路径是否正确!"; 
  } 

  /** 
  * 方法:移动文件 
  * @path  -- 原路径 
  * @newpath -- 新路径 
  * @type  -- 若目标目录不存在则新建 
  */
  function move_file($path,$newpath,$type=true) 
  { 
    if($type) $this->dir_mkdirs($newpath); 
    $this->off = @ftp_rename($this->conn_id,$path,$newpath); 
    if(!$this->off) echo "文件移动失败,请检查权限及原路径是否正确!"; 
  } 

  /** 
  * 方法:复制文件 
  * 说明:由于FTP无复制命令,本方法变通操作为:下载后再上传到新的路径 
  * @path  -- 原路径 
  * @newpath -- 新路径 
  * @type  -- 若目标目录不存在则新建 
  */
  function copy_file($path,$newpath,$type=true) 
  { 
    $downpath = "c:/tmp.dat"; 
    $this->off = @ftp_get($this->conn_id,$downpath,$path,FTP_BINARY);// 下载 
    if(!$this->off) echo "文件复制失败,请检查权限及原路径是否正确!"; 
    $this->up_file($downpath,$newpath,$type); 
  } 

  /** 
  * 方法:删除文件 
  * @path -- 路径 
  */
  function del_file($path) 
  { 
    $this->off = @ftp_delete($this->conn_id,$path); 
    if(!$this->off) echo "文件删除失败,请检查权限及路径是否正确!"; 
  } 

  /** 
  * 方法:生成目录 
  * @path -- 路径 
  */
  function dir_mkdirs($path) 
  { 
    $path_arr = explode('/',$path);       // 取目录数组 
    $file_name = array_pop($path_arr);      // 弹出文件名 
    $path_div = count($path_arr);        // 取层数 

    foreach($path_arr as $val)          // 创建目录 
    { 
      if(@ftp_chdir($this->conn_id,$val) == FALSE) 
      { 
        $tmp = @ftp_mkdir($this->conn_id,$val); 
        if($tmp == FALSE) 
        { 
          echo "目录创建失败,请检查权限及路径是否正确!"; 
          exit; 
        } 
        @ftp_chdir($this->conn_id,$val); 
      } 
    } 

    for($i=1;$i<=$path_div;$i++)         // 回退到根 
    { 
      @ftp_cdup($this->conn_id); 
    } 
  } 

  /** 
  * 方法:关闭FTP连接 
  */
  function close() 
  { 
    @ftp_close($this->conn_id); 
  } 
}
?>

How to use: Only upload and download are described. For other details, please refer to official documents and notes

    import("Common/Org/ftp");
    $ftp = new \ftp("host",port,"user","passwd");
    //上传文件
    $ftp->up_file("localpath","remotePath");
    //下载文件
    $ftp->copy_file("remotePath","localpath");
    //关闭FTP连接
    $ftp->close();

2、SFTP

  • Create a new php file sftp.class.php in the TP3.2 storage class file directory (Common/Org/)
<?php
/******************************************** 
* MODULE:SFTP类 
*******************************************/
class sftp{
    // 初始配置为NULL
    private $config =NULL ;
    // 连接为NULL
    private $conn = NULL;
    // 是否使用秘钥登陆
    private $use_pubkey_file= false;
    // 初始化
    public function init($config){
        $this->config = $config ;
    }
    // 连接ssh ,连接有两种方式(1) 使用密码
    // (2) 使用秘钥
    public function connect(){
        $methods['hostkey'] = $this->use_pubkey_file ? 'ssh-rsa' : [] ;
        $this->conn = ssh2_connect($this->config['host'], $this->config['port'], $methods);
        //(1) 使用秘钥的时候
        if($this->use_pubkey_file){
            // 用户认证协议
            $rc = ssh2_auth_pubkey_file($this->conn,$this->config['user'],$this->config['pubkey_file'],$this->config['privkey_file'],$this->config['passphrase']);
            //(2) 使用登陆用户名字和登陆密码
        }else{
            $rc = ssh2_auth_password( $this->conn, $this->config['user'],$this->config['passwd']);
        }
        return $rc ;
    }
    // 传输数据 传输层协议,获得数据
    public function download($remote, $local){
        return ssh2_scp_recv($this->conn, $remote, $local);
    }
    //传输数据 传输层协议,写入ftp服务器数据
    public function upload($remote, $local,$file_mode=0664){
        return ssh2_scp_send($this->conn, $local, $remote, $file_mode);
    }
    // 删除文件
    public function remove($remote){
        $sftp = ssh2_sftp($this->conn);
        $rc = false;
        if (is_dir("ssh2.sftp://{$sftp}/{$remote}")) {
            $rc = false ;
            // ssh 删除文件夹
            $rc = ssh2_sftp_rmdir($sftp, $remote);
        } else {
            // 删除文件
            $rc = ssh2_sftp_unlink($sftp, $remote);
        }
        return $rc;
    }
}
?>

How to use: Only upload and download are described. For other details, please refer to official documents and notes

    import("Common/Org/sftp");
    $config = array("host"=>"host","user"=>"","port"=>"","passwd"=>"");
    $handle = new \sftp();
    $handle->init($config);
    $rc = $handle->connect();
    //上传,成功返回true
    dump($handle->upload("remotePath","localPath"));exit;
    //下载,成功返回true
    dump($handle->download("remotePath","localPath"));exit;

PHP3 or above already has its own FTP extension. If the above FTP code cannot be used or an error is reported, please first check whether the php.ini file has FTP extension support enabled.

SFTP needs to install an extension when using it. The following is a brief description of the extension installation. If the extension is not installed, the following problems may occur: 
write picture description here
If you encounter this problem, it is necessary to install the extension.

Notes on compiling and installing PHP's SFTP extension library

1. Download the file:

wget --no-check-certificate https://www.libssh2.org/download/libssh2-1.8.0.tar.gz
wget http://pecl.php.net/get/ssh2-0.13.tgz  #1.0以上版本只支持 php7以上的 php

2. Install libssh2 and install SS2

tar -zxvf libssh2-1.4.2.tar.gz
cd libssh2-1.4.2
./configure --prefix=/usr/local/libssh2
make
make test
make install

3. SSH installation

tar -zxvf ssh2-0.12.tgz
cd ssh2-0.12
phpize(个人目录不同,例如:/usr/local/php/bin/phpize)
./configure --prefix=/usr/local/ssh2 --with-ssh2=/usr/local/libssh2 --with-php-config=/usr/local/php/bin/php-config   //找到php-config路径
make
make test  #这句可能会报错 但是不影响
make install

After installation is complete:

The rest is to modify the php.ini configuration file 
to find the php.ini file, open it and add:

extension=/usr/lib/php5/20121212/ssh2.so

 

Compilation problems may occur during the installation process. Different problems correspond to different solutions. Generally, gcc and openssl cannot find problems. The reason is that the extension was not installed correctly, just find the path.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325289799&siteId=291194637