您的位置:首页 > 编程语言 > PHP开发

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');
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  PHP