88 lines
2.9 KiB
PHP
88 lines
2.9 KiB
PHP
<?php
|
|
session_start();
|
|
require_once 'auth_check.php';
|
|
require_once 'db/config.php';
|
|
|
|
if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'admin') {
|
|
header('Location: login.php');
|
|
exit;
|
|
}
|
|
|
|
$error = '';
|
|
$success = '';
|
|
|
|
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['csv_file'])) {
|
|
$file = $_FILES['csv_file']['tmp_name'];
|
|
$handle = fopen($file, "r");
|
|
|
|
if ($handle !== FALSE) {
|
|
$pdoconfig = db();
|
|
$pdo = new PDO($pdoconfig['dsn'], $pdoconfig['user'], $pdoconfig['pass'], $pdoconfig['options']);
|
|
$pdo->beginTransaction();
|
|
|
|
// Skip header row
|
|
fgetcsv($handle, 1000, ",");
|
|
|
|
$created_count = 0;
|
|
$error_count = 0;
|
|
$errors = [];
|
|
|
|
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
|
|
$username = trim($data[0]);
|
|
$email = trim($data[1]);
|
|
$password = $data[2];
|
|
$role = trim($data[3]);
|
|
|
|
if (empty($username) || empty($email) || empty($password) || empty($role)) {
|
|
$errors[] = "Skipping row: required field is empty.";
|
|
$error_count++;
|
|
continue;
|
|
}
|
|
|
|
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
|
|
$errors[] = "Skipping row for email {$email}: invalid email format.";
|
|
$error_count++;
|
|
continue;
|
|
}
|
|
|
|
$stmt = $pdo->prepare('SELECT id FROM users WHERE username = :username OR email = :email');
|
|
$stmt->execute(['username' => $username, 'email' => $email]);
|
|
if ($stmt->fetch()) {
|
|
$errors[] = "Skipping row for user {$username}: username or email already exists.";
|
|
$error_count++;
|
|
continue;
|
|
}
|
|
|
|
$hashed_password = password_hash($password, PASSWORD_DEFAULT);
|
|
$stmt = $pdo->prepare('INSERT INTO users (username, email, password, role) VALUES (:username, :email, :password, :role)');
|
|
if ($stmt->execute(['username' => $username, 'email' => $email, 'password' => $hashed_password, 'role' => $role])) {
|
|
$created_count++;
|
|
} else {
|
|
$errors[] = "Failed to create user {$username}.";
|
|
$error_count++;
|
|
}
|
|
}
|
|
|
|
fclose($handle);
|
|
|
|
if ($error_count === 0) {
|
|
$pdo->commit();
|
|
$success = "{$created_count} users created successfully.";
|
|
} else {
|
|
$pdo->rollBack();
|
|
$error = "There were {$error_count} errors creating users. No users were created. Errors: <br>" . implode("<br>", $errors);
|
|
}
|
|
|
|
$_SESSION['upload_success'] = $success;
|
|
$_SESSION['upload_error'] = $error;
|
|
|
|
} else {
|
|
$_SESSION['upload_error'] = 'Failed to open CSV file.';
|
|
}
|
|
header("Location: manage_users.php");
|
|
exit;
|
|
} else {
|
|
header('Location: manage_users.php');
|
|
exit;
|
|
}
|