php 实现 ftp 和 sftp 上传下载文件

PHP之FTP、SFTP上传下载

对接三方时遇见接口采用文件加密后使用FTP或SFTP传输,使用PHP对接。所以产生了本篇文章(基于TP3.2)。本篇文章包括以下几点:

  • 基本代码
  • 使用方法
  • PHP之SFTP扩展库编译安装注意事项

转载请注明 —— [ 肖义熙 ]

一、PHP之FTP、SFTP代码,拷贝直接用

FTP及SFTP官方文档详见: 
http://php.net/manual/en/book.ftp.php

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

以下为本文最核心代码,拷贝直接使用:

1、FTP

  • TP3.2存放类文件目录下(Common/Org/)新建php文件: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); 
  } 
}
?>

使用方法:只说明上传、下载。其他请参考官方文档及注释

    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

  • TP3.2存放类文件目录下(Common/Org/)新建php文件 sftp.class.php
<?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;
    }
}
?>

使用方法:只说明上传、下载。其他请参考官方文档及注释

    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以上就已经自带FTP扩展,如果以上FTP代码无法使用或报错,请优先检测php.ini文件是否开启ftp扩展支持。

SFTP在使用时需要安装扩展,以下为扩展安装简述。没有安装扩展可能会出现以下问题: 
这里写图片描述
如果遇见这个问题时,那就是需要安装扩展了。

PHP之SFTP扩展库编译安装注意事项

1、下载文件:

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、安装 libssh2 在安装 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安装

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

安装完成后:

剩下就是修改php.ini配置文件 
找到php.ini文件,打开后加入:

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

安装过程中可能会出现编译问题,不同问题对应不同解决方式,一般会遇见gcc及openssl找不到问题。原因是安装这个扩展时没有正确安装,找到路径即可。

猜你喜欢

转载自my.oschina.net/u/2399303/blog/1806453