PHP FTP 文件上传

class Ftp
{
    public $config = [
        'debug' => true,
        'host' => '',
        'username' => '',
        'password' => '',
        'port' => ,
        'root' => '',
        'prefix_img_url' => ''
    ];

    public $error = '';

    public $connect = '';

    public function connect($host = '', $port = '', $user = '', $password = '')
    {
        $host = $host ? $host : $this->config['host'];
        $port = $port ? $port : $this->config['port'];
        $user = $user ? $user : $this->config['username'];
        $password = $password ? $password : $this->config['password'];

        // 连接FTP
        $conn_id = ftp_connect($host, $port);
        if (!$conn_id) {
            $this->error = "Couldn't connect to $host";
            return false;
        }

        // 登陆
        if (!ftp_login($conn_id, $user, $password)) {
            $this->error = "Couldn't connect as $user";
            return false;
        }

        // 打开被动传输
        ftp_pasv($conn_id, true);

        $this->connect = $conn_id;

        return true;
    }

    //   上传
    public function upload($romote_file, $local_file)
    {

        if (!file_exists($local_file)) {
            $this->error = "File not extsts: $local_file";
            return false;
        }

        if (substr($romote_file, 0, 1) == '/') {
            $romote_file = substr($romote_file, 1, strlen($romote_file) - 1);
        }
        // 转换成对应格式
        $fileEx = substr($romote_file, strrpos($romote_file, '.') + 1);
        $romote_file = date('YmdHis') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT) . '.' . $fileEx;

        $debug = $this->config['debug'] == false ? '' : 'test';
        $romote_path = $this->config['root'] . $debug . date('/Ym/') . $romote_file;

        if (!ftp_nlist($this->connect, $this->config['root'] . $debug . date('/Ym'))) {
            ftp_mkdir($this->connect, $this->config['root'] . $debug . date('/Ym'));
        }
        if (!ftp_put($this->connect, $romote_path, $local_file, FTP_BINARY)) {
            $this->error = "There was a problem while uploading $local_file,$romote_path";
            return false;
        }

        ftp_close($this->connect);

        return $this->config['prefix_img_url'] . $romote_path;
    }
}

使用方法:
 
$ftp = new Ftp();
$ftp->connect();
$ftp->upload('路径/线上文件.jpg','路径/本地.jpg');



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值