PHP文件上传封装
class FileUploader {
private $targetDirectory;
private $allowedExtensions;
private $maxFileSize;
public function __construct($targetDirectory, $allowedExtensions = array(), $maxFileSize = 1048576) {
$this->targetDirectory = $targetDirectory;
$this->allowedExtensions = $allowedExtensions;
$this->maxFileSize = $maxFileSize;
}
public function upload($fileInputName) {
if (!isset($_FILES[$fileInputName])) {
throw new Exception('File input not found.');
}
$file = $_FILES[$fileInputName];
$filename = $file['name'];
$fileTmpPath = $file['tmp_name'];
$fileSize = $file['size'];
$fileError = $file['error'];
// Validate file error
if ($fileError !== UPLOAD_ERR_OK) {
throw new Exception('File upload error: ' . $this->getFileErrorMessage($fileError));
}
// Validate file size
if ($fileSize > $this->maxFileSize) {
throw new Exception('File size exceeds the maximum limit.');
}
// Validate file extension
$fileExtension = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
if (!empty($this->allowedExtensions) && !in_array($fileExtension, $this->allowedExtensions)) {
throw new Exception('Invalid file extension.');
}
// Generate unique filename
$newFilename = uniqid() . '.' . $fileExtension;
$destinationPath = $this->targetDirectory . '/' . $newFilename;
// Move uploaded file to destination
if (!move_uploaded_file($fileTmpPath, $destinationPath)) {
throw new Exception('Failed to move uploaded file.');
}
return $newFilename;
}
private function getFileErrorMessage($errorCode) {
switch ($errorCode) {
case UPLOAD_ERR_INI_SIZE:
return 'The uploaded file exceeds the upload_max_filesize directive in php.ini.';
case UPLOAD_ERR_FORM_SIZE:
return 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.';
case UPLOAD_ERR_PARTIAL:
return 'The uploaded file was only partially uploaded.';
case UPLOAD_ERR_NO_FILE:
return 'No file was uploaded.';
case UPLOAD_ERR_NO_TMP_DIR:
return 'Missing a temporary folder.';
case UPLOAD_ERR_CANT_WRITE:
return 'Failed to write file to disk.';
case UPLOAD_ERR_EXTENSION:
return 'A PHP extension stopped the file upload.';
default:
return 'Unknown error occurred.';
}
}
}
使用示例:
$targetDirectory = '/path/to/uploads';
$allowedExtensions = array('jpg', 'png', 'gif');
$maxFileSize = 1048576; // 1MB
$fileUploader = new FileUploader($targetDirectory, $allowedExtensions, $maxFileSize);
try {
$uploadedFilename = $fileUploader->upload('file_input_name');
echo 'File uploaded successfully. Filename: ' . $uploadedFilename;
} catch (Exception $e) {
echo 'Error: ' . $e->getMessage();
}
在上述示例中,FileUploader
类封装了文件上传的功能。你可以通过在实例化 FileUploader
类时指定目标目录、允许的文件扩展名和最大文件大小来进行配置。然后,调用 `upload
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)