Correction status:Uncorrected
Teacher's comments:
class Upload
{
private $path;
private $size;
private $type;
private $error;
public function __construct($path, $size, $type)
{
$this->path = $path;
$this->size = $size;
$this->type = $type;
}
// 返回错误信息
public function getError()
{
return $this->error;
}
// 验证上传是否有误
public function checkError($files)
{
// 1. 验证错误号
if ($files['error'] != 0) {
switch ($files['error']) {
case 1:
$this->error = '文件大小超过了php.ini中允许的最大值,最大值是:'.ini_get('upload_max_filesize');
return false;
case 2:
$this->error = '文件大小超过了表单允许的最大值';
return false;
case 3:
$this->error = '只有部分文件上传成功';
return false;
case 4:
$this->error = '没有文件上传成功';
return false;
case 6:
$this->error = '找不到临时文件';
return false;
case 7:
$this->error = '文件写入失败';
return false;
default:
$this->error = '未知错误';
return false;
}
}
// 2. 验证格式
$info = finfo_open(FILEINFO_MIME_TYPE);
$mime = finfo_file($info, $files['tmp_name']);
if (!in_array($mime, $this->type)) {
$this->error = '只能上传'.implode(',', $this->type).'格式';
return false;
}
// 3. 验证大小
if ($files['size'] > $this->size) {
$this->error = '文件大小不能超过HTTP POST上传的';
return false;
}
if (!is_uploaded_file($files['tmp_name'])) {
$this->error = '文件不是HTTP POST上传的';
return false;
}
return true;
}
// 文件上传
public function uploadOne($files)
{
if ($this->checkError($files)) { // 没有错误就上传
$folderName = date('Y-m-d'); // 文件夹名
$folderPath = $this->path . $folderName; // 文件夹路径
if (!is_dir($this->path))
mkdir($this->path,0777);
if (!is_dir($folderPath))
mkdir($folderPath,0777);
$fileName = uniqid('', true) . strrchr($files['name'], '.'); //文件名
$filePath = "$folderPath / $fileName";
if (move_uploaded_file($files['tmp_name'], $filePath)) {
return "${$folderPath} / {$fileName}";
} else {
$this->error = '上传失败<br>';
return false;
}
}
return false;
}
}
2.上传页 index.html
<form action="doupload.php" method="post" enctype="multipart/form-data">
<input type="file" name="file" id="file">
<button type="submit" id="btn">上传</button>
</form>
3.处理上传 doupload.php
require 'Upload.php';
$path = './uploads/';
$size = 5242880;
$type = ['image/png','image/jpeg','image/gif','image/jpg','image/wbmp'];
$upload = new Upload($path, $size, $type);
$file = $_FILES['file'];
if ( $info = $upload->uploadOne($file)) {
echo '上传成功' . $info;
} else {
echo $upload->getError();
// 错误写入文件
file_put_contents('log.text', $upload->getError());