nhance-enrollment/app/Helpers/fileupload_helper.php

41 lines
1.2 KiB
PHP
Executable File

<?php
if (!function_exists('file_to_upload')) {
function file_to_upload($file, $allowedTypes = [], $uploadDirectory = '')
{
$uploadPath = ROOTPATH . 'public/uploads/' . $uploadDirectory;
// Check if the upload directory exists
if (!is_dir($uploadPath)) {
throw new \Exception('Upload directory does not exist.');
}
// Validate file type
if (!empty($allowedTypes) && !in_array($file->getClientMimeType(), $allowedTypes)) {
throw new \Exception('Invalid file type.');
}
// Generate a unique filename
$originalName = $file->getName();
$ext = pathinfo($originalName, PATHINFO_EXTENSION);
$baseName = pathinfo($originalName, PATHINFO_FILENAME);
$counter = 0;
$newName = $baseName . '.' . $ext;
while (file_exists($uploadPath . $newName)) {
$counter++;
$newName = $baseName . '_' . $counter . '.' . $ext;
}
// Move the file to the upload directory
try {
$file->move($uploadPath, $newName);
} catch (\Exception $e) {
throw new \Exception('Failed to upload file: ' . $e->getMessage());
}
return $uploadDirectory . $newName;
}
}