PHP 封装文件上传
controller.php
<?php
include 'Uploader.php';
$upload = new Uploader();
var_dump($upload->make());
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>文件上传</title>
</head>
<body>
<form action="controller.php" method="post" enctype="multipart/form-data">
<input type="file" name="img[]" id="">
<input type="file" name="img[]" id="">
<br>
<br>
<button type="submit"
style="
color: white;
background-color: crimson;
border-style: none;
height: 30px;
">提交上传</button>
</form>
</body>
</html>
Uploader.php
<?php
class Uploader
{
private $dir = null;
public function make()
{
$this->dir();
$files = $this->ext();
$endUploadFilePath = [];
foreach ($files as $file) {
if (is_uploaded_file($file['tmp_name'])) {
if (move_uploaded_file($file['tmp_name'], $this->dir . time() . rand() . '.' . pathinfo($file['name'])['extension'])) {
$endUploadFilePath[] = $this->dir . time() . rand(100, 999) . '.' . pathinfo($file['name'])['extension'];
}
} else {
return '请上传文件';
}
}
return $endUploadFilePath;
}
public function dir(): bool
{
$path = 'uploads' . DIRECTORY_SEPARATOR . date('y/d') . DIRECTORY_SEPARATOR;
$this->dir = $path;
return is_dir($path) or mkdir($path, 0755, true);
}
private function ext(): array
{
$files = [];
foreach ($_FILES as $field) {
if (is_array($field['name'])) {
foreach ($field['name'] as $id => $f) {
$files[] = [
'name' => $field['name'][$id],
'type' => $field['type'][$id],
'tmp_name' => $field['tmp_name'][$id],
'error' => $field['error'][$id],
'size' => $field['size'][$id]
];
}
} else {
$files[] = $field;
}
}
return $files;
}
}
|