一个简单实用的PHP文件上传类,支持单文件和多文件上传,支持文件类型和大小限制,自动创建上传目录。小白也能轻松上手,复制粘贴就能用!
## 功能特点
– 支持单文件上传
– 支持多文件上传
– 支持文件类型限制
– 支持文件大小限制
– 自动创建上传目录
– 完整的错误信息提示
## 效果预览
先给大家看看使用后的实际效果,心里有个底:

上图展示了单文件上传和多文件上传的实际效果,界面简洁美观,上传成功后会显示文件信息和保存路径。
## 详细使用教程(小白必看)
很多朋友刚接触PHP,可能不知道怎么用这个上传类。别担心,我手把手教你,从最基础的步骤开始,保证你一看就会!
### 第一步:准备工作
首先,你需要有一个PHP运行环境。如果你还没有,可以安装以下其中一个:
– **phpStudy**(推荐新手用,一键安装)
– **XAMPP**(功能全面)
– **WampServer**(Windows系统常用)
安装好之后,找到你的网站根目录(一般是www或者htdocs文件夹)。
### 第二步:创建文件
在你的网站根目录下,创建两个文件:
1. `FileUpload.php` – 这是上传类文件
2. `upload.php` – 这是上传处理和表单页面
### 第三步:复制上传类代码
把下面的完整代码复制到 `FileUpload.php` 文件中,保存好。(完整代码在文章最后面)
### 第四步:创建上传表单页面
在 `upload.php` 文件中,写入以下代码:
“`php
<?php
// 引入上传类
require_once ‘FileUpload.php’;
// 处理上传
if ($_POST) {
// 配置上传参数
$config = [
‘max_size’ => 2 * 1024 * 1024, // 最大2MB
‘allow_types’ => [‘jpg’, ‘jpeg’, ‘png’, ‘gif’, ‘txt’, ‘zip’, ‘rar’],
‘upload_path’ => ‘./uploads/’,
];
// 实例化上传类
$upload = new FileUpload($config);
// 单文件上传
if (isset($_FILES[‘file’]) && $_FILES[‘file’][‘error’] == 0) {
$result = $upload->upload($_FILES[‘file’]);
if ($result) {
echo ‘<p style=”color: green;”>上传成功!文件路径:’ . $result . ‘</p>’;
} else {
echo ‘<p style=”color: red;”>上传失败:’ . $upload->getError() . ‘</p>’;
}
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset=”UTF-8″>
<title>文件上传</title>
</head>
<body>
<h2>单文件上传</h2>
<form method=”post” enctype=”multipart/form-data”>
<input type=”file” name=”file”>
<button type=”submit”>上传</button>
</form>
</body>
</html>
“`
### 第五步:测试上传
1. 在浏览器中访问 `http://localhost/upload.php`
2. 点击”选择文件”按钮,选择一个图片或文本文件
3. 点击”上传”按钮
4. 如果看到绿色的”上传成功”提示,就说明成功了!
5. 你可以在网站根目录的 `uploads` 文件夹里找到上传的文件
### 第六步:多文件上传(进阶)
如果你想一次上传多个文件,可以用下面的代码:
“`php
<?php
require_once ‘FileUpload.php’;
if ($_POST) {
$config = [
‘max_size’ => 2 * 1024 * 1024,
‘allow_types’ => [‘jpg’, ‘png’, ‘gif’],
‘upload_path’ => ‘./uploads/’,
];
$upload = new FileUpload($config);
// 多文件上传
if (isset($_FILES[‘files’])) {
$results = $upload->uploadMulti($_FILES[‘files’]);
if ($results) {
echo ‘<p style=”color: green;”>成功上传了 ‘ . count($results) . ‘ 个文件:</p>’;
foreach ($results as $file) {
echo ‘<p>’ . $file . ‘</p>’;
}
} else {
echo ‘<p style=”color: red;”>上传失败:’ . $upload->getError() . ‘</p>’;
}
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset=”UTF-8″>
<title>多文件上传</title>
</head>
<body>
<h2>多文件上传</h2>
<form method=”post” enctype=”multipart/form-data”>
<input type=”file” name=”files[]” multiple>
<button type=”submit”>上传</button>
</form>
<p><small>提示:按住Ctrl键可以选择多个文件</small></p>
</body>
</html>
“`
### 常见问题解答
**Q: 上传失败,提示”文件大小超过限制”怎么办?**
A: 有两个地方可以调整:
1. 在PHP配置文件php.ini中修改 `upload_max_filesize` 和 `post_max_size`
2. 在代码中修改 `max_size` 参数
**Q: 上传的文件保存在哪里?**
A: 默认保存在网站根目录的 `uploads` 文件夹里,这个文件夹会自动创建,不用你手动建。
**Q: 我想限制只能上传图片,怎么改?**
A: 把 `allow_types` 改成只保留图片格式就行,比如:
“`php
‘allow_types’ => [‘jpg’, ‘jpeg’, ‘png’, ‘gif’],
“`
## 完整代码
下面是完整的FileUpload.php代码,直接复制就能用:
“`php
<?php
/**
* PHP文件上传类
* 支持单文件、多文件上传
* 支持文件类型、大小限制
* 支持自动创建目录
*/
class FileUpload {
private $maxSize = 2097152; // 最大2MB
private $allowTypes = [‘jpg’, ‘jpeg’, ‘png’, ‘gif’, ‘txt’, ‘zip’, ‘rar’];
private $uploadPath = ‘./uploads/’;
private $error = ”;
/**
* 构造函数
* @param array $config 配置项
*/
public function __construct($config = []) {
if (isset($config[‘max_size’])) {
$this->maxSize = $config[‘max_size’];
}
if (isset($config[‘allow_types’])) {
$this->allowTypes = $config[‘allow_types’];
}
if (isset($config[‘upload_path’])) {
$this->uploadPath = $config[‘upload_path’];
}
}
/**
* 上传单个文件
* @param array $file $_FILES中的文件
* @return string|false 成功返回文件路径,失败返回false
*/
public function upload($file) {
// 检查是否有错误
if ($file[‘error’] != UPLOAD_ERR_OK) {
$this->error = $this->getErrorMsg($file[‘error’]);
return false;
}
// 检查文件大小
if ($file[‘size’] > $this->maxSize) {
$this->error = ‘文件大小超过限制’;
return false;
}
// 获取文件扩展名
$ext = strtolower(pathinfo($file[‘name’], PATHINFO_EXTENSION));
// 检查文件类型
if (!in_array($ext, $this->allowTypes)) {
$this->error = ‘不允许的文件类型’;
return false;
}
// 创建上传目录
if (!is_dir($this->uploadPath)) {
mkdir($this->uploadPath, 0755, true);
}
// 生成文件名
$filename = uniqid() . ‘.’ . $ext;
$filepath = $this->uploadPath . $filename;
// 移动文件
if (move_uploaded_file($file[‘tmp_name’], $filepath)) {
return $filepath;
} else {
$this->error = ‘文件上传失败’;
return false;
}
}
/**
* 上传多个文件
* @param array $files $_FILES中的文件数组
* @return array 成功上传的文件路径数组
*/
public function uploadMulti($files) {
$result = [];
// 重新整理文件数组
$fileArray = $this->rearrangeFiles($files);
foreach ($fileArray as $file) {
$path = $this->upload($file);
if ($path) {
$result[] = $path;
}
}
return $result;
}
/**
* 获取错误信息
* @return string
*/
public function getError() {
return $this->error;
}
/**
* 获取错误信息
* @param int $code 错误代码
* @return string
*/
private function getErrorMsg($code) {
$errors = [
UPLOAD_ERR_INI_SIZE => ‘文件大小超过php.ini限制’,
UPLOAD_ERR_FORM_SIZE => ‘文件大小超过表单限制’,
UPLOAD_ERR_PARTIAL => ‘文件只有部分被上传’,
UPLOAD_ERR_NO_FILE => ‘没有文件被上传’,
UPLOAD_ERR_NO_TMP_DIR => ‘找不到临时文件夹’,
UPLOAD_ERR_CANT_WRITE => ‘文件写入失败’,
];
return isset($errors[$code]) ? $errors[$code] : ‘未知错误’;
}
/**
* 重新整理多文件上传数组
* @param array $files
* @return array
*/
private function rearrangeFiles($files) {
$result = [];
if (is_array($files[‘name’])) {
$count = count($files[‘name’]);
for ($i = 0; $i < $count; $i++) {
$result[] = [
‘name’ => $files[‘name’][$i],
‘type’ => $files[‘type’][$i],
‘tmp_name’ => $files[‘tmp_name’][$i],
‘error’ => $files[‘error’][$i],
‘size’ => $files[‘size’][$i],
];
}
} else {
$result[] = $files;
}
return $result;
}
}
“`
## 总结
这个PHP文件上传类非常实用,不管是做图片上传、附件上传还是文件管理系统都能用得上。代码简洁,功能全面,新手也能快速上手。
如果你觉得有用,记得收藏一下,以后做项目的时候直接拿来用就行!
一个简单实用的PHP文件上传类,支持单文件和多文件上传,支持文件类型和大小限制,自动创建上传目录。
## 功能特点
– 支持单文件上传
– 支持多文件上传
– 支持文件类型限制
– 支持文件大小限制
– 自动创建上传目录
– 完整的错误信息提示
## 使用方法
<?php
class FileUpload {
private $maxSize = 2097152; // 2MB
private $allowTypes = ['jpg', 'png', 'gif', 'txt', 'zip'];
private $uploadPath = './uploads/';
private $error = '';
public function __construct($config = []) {
if (isset($config['max_size'])) $this->maxSize = $config['max_size'];
if (isset($config['allow_types'])) $this->allowTypes = $config['allow_types'];
if (isset($config['upload_path'])) $this->uploadPath = $config['upload_path'];
}
public function upload($file) {
if ($file['error'] != UPLOAD_ERR_OK) {
$this->error = '上传错误';
return false;
}
if ($file['size'] > $this->maxSize) {
$this->error = '文件过大';
return false;
}
$ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
if (!in_array($ext, $this->allowTypes)) {
$this->error = '不允许的文件类型';
return false;
}
if (!is_dir($this->uploadPath)) {
mkdir($this->uploadPath, 0755, true);
}
$filename = uniqid() . '.' . $ext;
$filepath = $this->uploadPath . $filename;
if (move_uploaded_file($file['tmp_name'], $filepath)) {
return $filepath;
}
return false;
}
public function getError() {
return $this->error;
}
}








暂无评论内容