sftp 上传类

<?php
/**
 * Created by PhpStorm.
 * User: lixingbo
 * Date: 2019/2/22
 * Time: 下午1:41
 */

namespace App\Libs;

class FtpException extends \Exception
{
}

class Sftp
{
    private $conn    = NULL;
    private $ressftp = NULL;

    public function __construct($host, $port = 22)
    {
        $this->connect($host, $port);
    }

    public function connect($host, $port)
    {
        $this->conn = ssh2_connect($host, $port); //sftp 要用 ssh2_connect 不能用ftp_ssl_connect

        if (!$this->conn) {
            throw new FtpException('Unable to connect');
        }
    }

    public function login($username, $password)
    {
        if (ssh2_auth_password($this->conn, $username, $password)) {
            $this->ressftp = ssh2_sftp($this->conn);
        } else {
            throw new FtpException('username or password error');
        }
    }

    private function dist($remote)
    {
        return "ssh2.sftp://" . intval($this->ressftp) . $remote;//这里要intval 否则:failed to open stream: operation failed
    }

    public function get($remote, $local)
    {
        return copy(self::dist($remote), $local);
    }

    public function put($local, $remote)
    {
        return copy($local, self::dist($remote));
    }

    public function mkdir($path)
    {
        ssh2_sftp_mkdir($this->ressftp, $path, 0777, true);
    }

    public function exits($file)
    {
        return file_exists(self::dist($file));
    }

    public function delete($file)
    {
        return ssh2_sftp_unlink($this->ressftp, $file);
    }
}
本作品采用《CC 协议》,转载必须注明作者和本文链接
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!