35311-vm/upload_document.php
2025-10-30 00:12:08 +00:00

66 lines
2.3 KiB
PHP

<?php
session_start();
require_once 'db/config.php';
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
header('Location: index.php');
exit;
}
if (!isset($_SESSION['user_id']) || $_SESSION['user_role'] !== 'partner') {
header('HTTP/1.1 403 Forbidden');
exit("Access denied.");
}
$resident_id = isset($_POST['resident_id']) ? (int)$_POST['resident_id'] : 0;
$description = isset($_POST['description']) ? trim($_POST['description']) : '';
if ($resident_id === 0 || empty($description) || !isset($_FILES['document']) || $_FILES['document']['error'] !== UPLOAD_ERR_OK) {
header("Location: manage_documents.php?resident_id={$resident_id}&error=invalid_upload");
exit;
}
$file = $_FILES['document'];
$upload_dir = __DIR__ . '/uploads/documents/';
$original_name = basename($file['name']);
$file_extension = pathinfo($original_name, PATHINFO_EXTENSION);
$unique_name = uniqid('', true) . '.' . $file_extension;
$target_path = $upload_dir . $unique_name;
// Basic security checks
$allowed_extensions = ['pdf', 'doc', 'docx', 'jpg', 'jpeg', 'png'];
if (!in_array(strtolower($file_extension), $allowed_extensions)) {
header("Location: manage_documents.php?resident_id={$resident_id}&error=invalid_file_type");
exit;
}
if ($file['size'] > 5 * 1024 * 1024) { // 5MB limit
header("Location: manage_documents.php?resident_id={$resident_id}&error=file_too_large");
exit;
}
if (move_uploaded_file($file['tmp_name'], $target_path)) {
try {
$pdo = db();
$partner_id = null;
$stmt = $pdo->prepare("SELECT id FROM partners WHERE user_id = ?");
$stmt->execute([$_SESSION['user_id']]);
$partner_id = $stmt->fetchColumn();
$sql = "INSERT INTO documents (resident_id, partner_id, file_name, file_path, description) VALUES (?, ?, ?, ?, ?)";
$stmt = $pdo->prepare($sql);
$stmt->execute([$resident_id, $partner_id, $original_name, $target_path, $description]);
header("Location: manage_documents.php?resident_id={$resident_id}&success=uploaded");
exit;
} catch (PDOException $e) {
// Clean up the uploaded file if DB insert fails
unlink($target_path);
header("Location: manage_documents.php?resident_id={$resident_id}&error=db_error");
exit;
}
} else {
header("Location: manage_documents.php?resident_id={$resident_id}&error=upload_failed");
exit;
}