static-variables / jweb /ac1 /src /api /upload_handler.php
fellybikush's picture
Upload 99 files
0dff816 verified
raw
history blame
2.22 kB
<?php
session_start();
if (!isset($_SESSION['logged_in']) || $_SESSION['logged_in'] !== true) {
header('HTTP/1.1 403 Forbidden');
exit('Access denied');
}
class FileUploader {
private $uploadDir = '../../uploads/claims/';
private $allowedTypes = ['jpg', 'jpeg', 'png', 'pdf', 'doc', 'docx'];
private $maxSize = 5 * 1024 * 1024; // 5MB
public function __construct() {
// Create upload directory if it doesn't exist
if (!file_exists($this->uploadDir)) {
mkdir($this->uploadDir, 0755, true);
}
}
public function upload($file) {
try {
// Check for errors
if ($file['error'] !== UPLOAD_ERR_OK) {
throw new Exception('Upload error: ' . $file['error']);
}
// Check file size
if ($file['size'] > $this->maxSize) {
throw new Exception('File size exceeds maximum limit of 5MB');
}
// Check file type
$fileExtension = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
if (!in_array($fileExtension, $this->allowedTypes)) {
throw new Exception('Invalid file type. Allowed types: ' . implode(', ', $this->allowedTypes));
}
// Generate unique filename
$filename = uniqid() . '_' . time() . '.' . $fileExtension;
$filepath = $this->uploadDir . $filename;
// Move uploaded file
if (!move_uploaded_file($file['tmp_name'], $filepath)) {
throw new Exception('Failed to move uploaded file');
}
return $filename;
} catch (Exception $e) {
error_log("File Upload Error: " . $e->getMessage());
return false;
}
}
}
// Handle file upload via AJAX
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['evidence_file'])) {
$uploader = new FileUploader();
$filename = $uploader->upload($_FILES['evidence_file']);
if ($filename) {
echo json_encode(['success' => true, 'filename' => $filename]);
} else {
echo json_encode(['success' => false, 'message' => 'File upload failed']);
}
exit;
}
?>