Files
willes_AI/inc/php/register.php

79 lines
2.5 KiB
PHP

<?php
session_start();
require_once($_SERVER['DOCUMENT_ROOT'] . '/db.php');
$errors = [];
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$username = trim($_POST['username'] ?? '');
$email = trim($_POST['email'] ?? '');
$confirm_email = trim($_POST['confirm_email'] ?? '');
$password = $_POST['password'] ?? '';
$age = (int) ($_POST['age'] ?? 0);
$captcha = $_POST['g-recaptcha-response'] ?? '';
// Basic validation
if (empty($username) || empty($email) || empty($confirm_email) || empty($password) || empty($age)) {
$errors[] = "All fields are required.";
}
if ($email !== $confirm_email) {
$errors[] = "Emails do not match.";
}
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors[] = "Invalid email format.";
}
if (strlen($password) < 6) {
$errors[] = "Password must be at least 6 characters.";
}
if ($age < 16) {
$errors[] = "You must be at least 16 years old to register.";
}
// CAPTCHA validation
$captcha_secret = '6LeIxAcTAAAAAGG-vFI1TnRWxMZNFuojJ4WifJWe'; // Google's test secret key
$captcha_response = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret={$captcha_secret}&response={$captcha}");
$captcha_data = json_decode($captcha_response);
if (!$captcha_data->success) {
$errors[] = "CAPTCHA verification failed.";
}
if (empty($errors)) {
$conn = getConnection();
// Check for existing user
$stmt = $conn->prepare("SELECT id FROM users WHERE email = :email OR username = :username");
$stmt->execute(['email' => $email, 'username' => $username]);
if ($stmt->fetch()) {
$errors[] = "Email or username already in use.";
} else {
$hash = password_hash($password, PASSWORD_BCRYPT, ['cost' => 12]);
$uniqueId = bin2hex(random_bytes(16));
$insert = $conn->prepare("INSERT INTO users (username, email, password, uniqueid) VALUES (:username, :email, :password, :uniqueid)");
$insert->execute([
'username' => $username,
'email' => $email,
'password' => $hash,
'uniqueid' => $uniqueId,
]);
$_SESSION['user_id'] = $conn->lastInsertId();
$_SESSION['uniqueid'] = $uniqueId;
header("Location: /home.php");
exit();
}
}
$_SESSION['register_error'] = implode("<br>", $errors);
header("Location: /landing.php");
exit();
}
?>