File "registration.php"

Full Path: /home/ccipcixf/public_html/miportal/registration.php
File size: 2.32 KB
MIME-type: text/x-php
Charset: utf-8

<?php
session_start(); // Start the session to store success messages
include("admin/includes/config.php");

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $username = trim($_POST['user_name']);
    $email = trim($_POST['user_email']);
    $password = $_POST['user_password'];

    // Basic validation
    if (empty($username) || empty($email) || empty($password)) {
        $_SESSION['error'] = "All fields are required.";
        header("Location: sign-up.php");
        exit;
    }

    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $_SESSION['error'] = "Invalid email format.";
        header("Location: sign-up.php");
        exit;
    }

    if (strlen($password) < 8) {
        $_SESSION['error'] = "Password must be at least 8 characters long.";
        header("Location: sign-up.php");
        exit;
    }

    // Check if email or username already exists in the database
    $stmt = $pdo->prepare("SELECT user_id FROM tb_user WHERE user_email = :user_email OR username = :username");
    $stmt->execute(['user_email' => $email, 'username' => $username]);
    $existingUser = $stmt->fetch();

    if ($existingUser) {
        // If user with the same email or username already exists
        if ($existingUser['user_email'] == $email) {
            $_SESSION['error'] = "This email is already registered.";
        } else {
            $_SESSION['error'] = "This username is already taken.";
        }
        header("Location: sign-up.php");
        exit;
    }

    // Hash password and insert user
    $hashed_password = password_hash($password, PASSWORD_BCRYPT);
    $role = 'user';

    try {
        $stmt = $pdo->prepare("INSERT INTO tb_user (username, user_email, password, role) VALUES (:username, :user_email, :password, :role)");
        $stmt->execute([
            'username' => $username,
            'user_email' => $email,
            'password' => $hashed_password,
            'role' => $role
        ]);

        // Store success message in session
        $_SESSION['registered'] = "Registration successful. Please Login to Setup Your Profile";
        header("Location: sign-up.php");
        exit;
    } catch (PDOException $e) {
        $_SESSION['error'] = "An error occurred. Please try again later.";
        header("Location: sign-up.php");
        exit;
    }
}