35049-vm/upload_csv.php
Flatlogic Bot 119d467b75 v2.0
2025-10-19 03:32:56 +00:00

77 lines
2.3 KiB
PHP

<?php
require_once __DIR__ . '/db/config.php';
// Basic validation
if ($_SERVER['REQUEST_METHOD'] !== 'POST' || !isset($_FILES['csvFile'])) {
header('Location: analyst_dashboard.php?error=' . urlencode('Invalid request.'));
exit;
}
$file = $_FILES['csvFile'];
// Check for upload errors
if ($file['error'] !== UPLOAD_ERR_OK) {
header('Location: analyst_dashboard.php?error=' . urlencode('File upload error: ' . $file['error']));
exit;
}
// Check file type
$mime_type = mime_content_type($file['tmp_name']);
if ($mime_type !== 'text/csv' && $mime_type !== 'text/plain') {
header('Location: analyst_dashboard.php?error=' . urlencode('Invalid file type. Please upload a CSV file.'));
exit;
}
$handle = fopen($file['tmp_name'], 'r');
if ($handle === false) {
header('Location: analyst_dashboard.php?error=' . urlencode('Could not open the uploaded file.'));
exit;
}
// Validate header
$header = fgetcsv($handle);
if ($header === false || count($header) !== 1 || strtolower(trim($header[0])) !== 'name') {
fclose($handle);
header('Location: analyst_dashboard.php?error=' . urlencode('Invalid CSV header. The first column must be "Name".'));
exit;
}
$pdo = db();
$stmt = $pdo->prepare("INSERT INTO submissions (name) VALUES (:name)");
$importedCount = 0;
$rowCount = 0;
while (($data = fgetcsv($handle)) !== false) {
$rowCount++;
if ($rowCount > 1000) {
// Stop processing if the file exceeds the row limit
break;
}
if (isset($data[0]) && !empty(trim($data[0]))) {
try {
$stmt->execute(['name' => trim($data[0])]);
$importedCount++;
} catch (PDOException $e) {
// You might want to log this error instead of ignoring it
// error_log("CSV Import Error: " . $e->getMessage());
continue; // Continue to the next row
}
}
}
fclose($handle);
// Trigger the background worker now that new submissions are in
if ($importedCount > 0) {
shell_exec('php /home/ubuntu/executor/workspace/worker.php > /dev/null 2>&1 &');
}
if ($rowCount > 1000) {
header('Location: analyst_dashboard.php?error=' . urlencode('CSV file exceeds the 1000-row limit. Only the first 1000 rows were processed.') . '&success=' . $importedCount);
} else {
header('Location: analyst_dashboard.php?success=' . $importedCount);
}
exit;