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