34918-vm/upload_submission.php
2025-10-13 09:51:27 +00:00

55 lines
1.7 KiB
PHP

<?php
session_start();
require_once 'db/config.php';
if (!isset($_SESSION['user_id'])) {
header("location: login.php");
exit;
}
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['competition_id']) && isset($_FILES['submission_file'])) {
$user_id = $_SESSION['user_id'];
$competition_id = $_POST['competition_id'];
$file = $_FILES['submission_file'];
// File upload error handling
if ($file['error'] !== UPLOAD_ERR_OK) {
// Handle upload error
header("location: user_dashboard.php?upload_error=1");
exit;
}
// Create uploads directory if it doesn't exist
$upload_dir = 'uploads/';
if (!is_dir($upload_dir)) {
mkdir($upload_dir, 0775, true);
}
// Generate a unique filename
$file_extension = pathinfo($file['name'], PATHINFO_EXTENSION);
$unique_filename = uniqid('submission_', true) . '.' . $file_extension;
$file_path = $upload_dir . $unique_filename;
// Move the file to the uploads directory
if (move_uploaded_file($file['tmp_name'], $file_path)) {
try {
$pdo = db();
$stmt = $pdo->prepare("INSERT INTO competition_submissions (user_id, competition_id, file_path) VALUES (?, ?, ?)");
$stmt->execute([$user_id, $competition_id, $file_path]);
} catch (PDOException $e) {
// Handle DB error
// You might want to log this error
// If DB insert fails, you might want to delete the uploaded file
unlink($file_path);
header("location: user_dashboard.php?upload_error=2");
exit;
}
}
header("location: user_dashboard.php");
exit;
}
header("location: user_dashboard.php");
exit;