PHP FTP 文件上传
2016-07-29 16:06
549 查看
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');
相关文章推荐
- 一个关于if else容易迷惑的问题
- PHP5.2.*防止Hash冲突拒绝服务攻击的Patch
- 深入理解PHP之匿名函数
- JSP/PHP基于Ajax的分页功能实现
- 关于PHP通过PDO用中文条件查询MySQL的问题。
- 什么是设计模式
- PHP数据库长连接mysql_pconnect的细节
- Php Installing An Expansion
- rem : web app适配的秘密武器
- jquery高级应用之Deferred对象
- 关于浮动与清除浮动,你应该知道的
- 数组reduce方法的高级技巧
- php7 读取php.ini[4]
- PHP+Apache在Windows 9x下的安装和配置
- IIS 6 的 PHP 最佳配置方法
- 安装Apache和PHP的一些补充
- Linux Apache+MySQL+PHP
- 建立Apache+PHP+MySQL数据库驱动的动态网站