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');