53 lines
1.5 KiB
PHP
53 lines
1.5 KiB
PHP
<?php
|
|
session_start();
|
|
require_once 'includes/globals.php';
|
|
require_once 'vendor/autoload.php';
|
|
|
|
use DJMixHosting\Database;
|
|
|
|
if (!isset($_SESSION['user'])) {
|
|
header("Location: login.php");
|
|
exit;
|
|
}
|
|
|
|
if ($_SERVER['REQUEST_METHOD'] !== 'POST' || !isset($_POST['new_username']) || empty($_POST['new_username'])) {
|
|
$_SESSION['error'] = "New username is required.";
|
|
header("Location: profile.php");
|
|
exit;
|
|
}
|
|
|
|
$new_username = trim($_POST['new_username']);
|
|
|
|
// Validate username (for example, only alphanumeric and underscores, 3-25 characters)
|
|
if (!preg_match('/^[a-zA-Z0-9_]{3,25}$/', $new_username)) {
|
|
$_SESSION['error'] = "Invalid username format.";
|
|
header("Location: profile.php");
|
|
exit;
|
|
}
|
|
|
|
$db = new Database($config);
|
|
$userId = $_SESSION['user']['id'];
|
|
|
|
// Check if the new username already exists (excluding the current user)
|
|
$stmt = $db->prepare("SELECT id FROM users WHERE username = ? AND id != ?");
|
|
$stmt->bind_param("si", $new_username, $userId);
|
|
$stmt->execute();
|
|
$result = $stmt->get_result();
|
|
if ($result->num_rows > 0) {
|
|
$_SESSION['error'] = "Username already taken.";
|
|
header("Location: profile.php");
|
|
exit;
|
|
}
|
|
$stmt->close();
|
|
|
|
// Update the username in the database
|
|
$stmt = $db->prepare("UPDATE users SET username = ? WHERE id = ?");
|
|
$stmt->bind_param("si", $new_username, $userId);
|
|
$stmt->execute();
|
|
$stmt->close();
|
|
|
|
// Update session data
|
|
$_SESSION['user']['username'] = $new_username;
|
|
$_SESSION['success'] = "Username updated successfully.";
|
|
header("Location: profile.php");
|
|
exit;
|