75 lines
2.4 KiB
PHP
75 lines
2.4 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') {
|
|
$username = trim($_POST['username']);
|
|
$password = $_POST['password'];
|
|
$role = $_POST['role'];
|
|
|
|
if (empty($username) || empty($password) || empty($role)) {
|
|
$error = 'All fields are required.';
|
|
} else {
|
|
$pdo = db();
|
|
|
|
$stmt = $pdo->prepare('SELECT id FROM users WHERE username = :username');
|
|
$stmt->execute(['username' => $username]);
|
|
if ($stmt->fetch()) {
|
|
$error = 'Username or email already exists.';
|
|
} else {
|
|
$hashed_password = password_hash($password, PASSWORD_DEFAULT);
|
|
$stmt = $pdo->prepare('INSERT INTO users (username, password, role) VALUES (:username, :password, :role)');
|
|
if ($stmt->execute(['username' => $username, 'password' => $hashed_password, 'role' => $role])) {
|
|
$success = 'User created successfully.';
|
|
} else {
|
|
$error = 'Failed to create user.';
|
|
}
|
|
}
|
|
}
|
|
}
|
|
?>
|
|
|
|
<?php include 'header.php'; ?>
|
|
|
|
<div class="container mt-4">
|
|
<h2>Create User</h2>
|
|
|
|
<?php if ($error): ?>
|
|
<div class="alert alert-danger"><?php echo $error; ?></div>
|
|
<?php endif; ?>
|
|
<?php if ($success): ?>
|
|
<div class="alert alert-success"><?php echo $success; ?></div>
|
|
<?php endif; ?>
|
|
|
|
<form action="create_user.php" method="post">
|
|
<div class="form-group">
|
|
<label for="username">Username</label>
|
|
<input type="text" name="username" class="form-control" id="username" required>
|
|
</div>
|
|
|
|
<div class="form-group">
|
|
<label for="password">Password</label>
|
|
<input type="password" name="password" class="form-control" id="password" required>
|
|
</div>
|
|
<div class="form-group">
|
|
<label for="role">Role</label>
|
|
<select name="role" class="form-control" id="role">
|
|
<option value="user">User</option>
|
|
<option value="admin">Admin</option>
|
|
</select>
|
|
</div>
|
|
<button type="submit" class="btn btn-primary">Create User</button>
|
|
<a href="manage_users.php" class="btn btn-secondary">Back to Manage Users</a>
|
|
</form>
|
|
</div>
|
|
|
|
<?php include 'footer.php'; ?>
|