coupon/register.php

103 lines
3.8 KiB
PHP
Executable File

<?php
require_once __DIR__ . '/config/db.php';
require_once __DIR__ . '/includes/functions.php';
if (isset($_SESSION['user_id'])) {
redirect('index.php');
}
$error = '';
$success = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$username = trim($_POST['username'] ?? '');
$password = $_POST['password'] ?? '';
$confirm = $_POST['confirm'] ?? '';
$invite = trim($_POST['invite'] ?? '');
if ($username === '' || $password === '' || $confirm === '' || $invite === '') {
$error = '请填写所有字段';
} elseif (strlen($username) < 3 || strlen($username) > 20) {
$error = '用户名长度3-20个字符';
} elseif (strlen($password) < 6) {
$error = '密码长度至少6位';
} elseif ($password !== $confirm) {
$error = '两次密码输入不一致';
} else {
// 检查用户名是否已存在
$stmt = $pdo->prepare('SELECT id FROM users WHERE username = ?');
$stmt->execute([$username]);
if ($stmt->fetch()) {
$error = '用户名已存在';
} else {
$pdo->beginTransaction();
try {
// 验证邀请码(次数校验:未超限 或 不限次数)
$stmt = $pdo->prepare("SELECT id, max_uses, used_count FROM invite_codes WHERE code = ? AND (used_count < max_uses OR max_uses = 0) FOR UPDATE");
$stmt->execute([$invite]);
$ic = $stmt->fetch();
if (!$ic) {
$error = '邀请码无效或已超出使用次数';
$pdo->rollBack();
} else {
$hash = password_hash($password, PASSWORD_DEFAULT);
$stmt = $pdo->prepare('INSERT INTO users (username, password) VALUES (?, ?)');
$stmt->execute([$username, $hash]);
// 增加邀请码使用次数
$stmt = $pdo->prepare('UPDATE invite_codes SET used_count = used_count + 1 WHERE id = ?');
$stmt->execute([$ic['id']]);
$pdo->commit();
redirect('login.php');
}
} catch (Exception $e) {
$pdo->rollBack();
$error = '注册失败,请重试';
}
}
}
}
?><!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>注册 - 兑换码管理系统</title>
<link rel="stylesheet" href="assets/css/style.css">
</head>
<body class="auth-page">
<div class="auth-card">
<h1>用户注册</h1>
<?php if ($error): ?>
<div class="alert alert-danger"><?= h($error) ?></div>
<?php endif; ?>
<?php if ($success): ?>
<div class="alert alert-success"><?= h($success) ?></div>
<div class="auth-footer"><a href="login.php">前往登录</a></div>
<?php else: ?>
<form method="post">
<div class="form-group">
<label>用户名</label>
<input type="text" name="username" class="form-control" required minlength="3" maxlength="20">
</div>
<div class="form-group">
<label>密码</label>
<input type="password" name="password" class="form-control" required minlength="6">
</div>
<div class="form-group">
<label>确认密码</label>
<input type="password" name="confirm" class="form-control" required>
</div>
<div class="form-group">
<label>邀请码</label>
<input type="text" name="invite" class="form-control" required>
</div>
<button type="submit" class="btn btn-primary">注 册</button>
</form>
<div class="auth-footer">已有账号?<a href="login.php">立即登录</a></div>
<?php endif; ?>
</div>
</body>
</html>