sftp 上傳類

1711293058發表於2019-10-30
<?php
/**
 * Created by PhpStorm.
 * User: blue.li
 * 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');
        }
    }

    public function get($remote, $local)
    {
        return copy("ssh2.sftp://" . intval($this->ressftp) . $remote, $local);
    }

    public function put($local, $remote)
    {
        return copy($local, "ssh2.sftp://" . intval($this->ressftp) . $remote);//這裡要intval 否則:failed to open stream: operation failed
    }

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

    public function exits($file)
    {
        return file_exists("ssh2.sftp://" . intval($this->ressftp) . $file);
    }

    public function delete($file)
    {
        return ssh2_sftp_unlink($this->ressftp, $file);
    }
}

相關文章