PHP7 SFTP下载文件并重命名该下载文件

SFTP类

 '',//sftp服务器地址
        'port' => ,//sftp服务器端口
        'username' => '', //sftp服务器用户名
        'password' => '' //sftp服务器密码
    ];

    // 连接为NULL
    private $conn = NULL;

    // 初始化
    public function __construct()
    {
        $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']))
        {
            echo json_encode([
                'code' => 500,
                'msg'  => '无法在服务器进行身份验证',
                'data' => null
            ]);die;
        }
    }

    // 传输数据 传输层协议,获得数据
    public function downftp($remote, $local)
    {
        $ressftp = ssh2_sftp($this->conn);
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename='."ssh2.sftp://".$ressftp."/upload/".$remote);
        header('Content-Transfer-Encoding: binary');
        Header("Accept-Ranges: bytes");
        header('Content-Disposition: attachment; filename=' . $local);
        header('Content-Type: application/octet-stream; name=' . $local);
        readfile("ssh2.sftp://".$ressftp."/upload/".$remote);

        /**
         * 从sftp服务器上下在文件,并保存的相应的目录
         */
        //return copy("ssh2.sftp://".$ressftp."/upload/".$remote, __DIR__.'/../../public/'.$local);
        //return copy("ssh2.sftp://".$ressftp."/upload/".$remote, $local);
        //return ssh2_scp_recv($this->conn, $remote, $local);
    }

    // 传输数据 传输层协议,写入ftp服务器数据
    public function upftp( $local,$remote, $file_mode = 0777)
    {
        $ressftp = ssh2_sftp($this->conn);
        return copy($local,"ssh2.sftp://{$ressftp}".'gongwenliuzhuan/upload/'.$remote);
    }

}

下载sftp服务上的文件的接口的文件
传相应的参数即可
如果需要检测sftp服务器上是否有该文件,请自行处理。

 500,
        'msg'  => 'sftpFileName is null',
        'data' => null
    ]);die;
}

//下载重命名
//$down_name = __DIR__.'/../../../public/'.$sftp_name;
//下载文件名
$new_name = trim($_GET['new_name']);
//下载文件类型
$type = strtolower(trim($_GET['type']));

if ($new_name == ''){
    echo json_encode([
        'code' => 500,
        'msg'  => 'newFileName is null',
        'data' => null
    ]);die;
}

if ($type == ''){
    echo json_encode([
        'code' => 500,
        'msg'  => 'fileType is null',
        'data' => null
    ]);die;
}

$down_name = $new_name.'.'.$type;
$my_sftp->downftp($sftp_name,$down_name);

你可能感兴趣的:(PHP,sftp,php)