diff options
author | Cflip <36554078+cflip@users.noreply.github.com> | 2021-01-23 11:56:41 -0700 |
---|---|---|
committer | Cflip <36554078+cflip@users.noreply.github.com> | 2021-01-23 11:56:41 -0700 |
commit | 0b26a9cd485d5b1ed509d9da998780d8b658eb8a (patch) | |
tree | a45cea3270081ba25b64723cda0c58671f45f674 | |
parent | 40b0ed967818fd3f0568ef8e4b42bf13d4077dad (diff) |
Improved validation in signup page
-rw-r--r-- | register.php | 46 |
1 files changed, 38 insertions, 8 deletions
diff --git a/register.php b/register.php index d167c2e..a318170 100644 --- a/register.php +++ b/register.php @@ -11,15 +11,32 @@ <input type="password" name="user_pass_check"><br> <input type="submit" name="submit"> </form> + <br> <?php include_once 'includes/db_inc.php'; -function validate($data) { - $data = trim($data); - $data = stripslashes($data); - $data = htmlspecialchars($data); - return $data; +function username_exists($dbc, $user_name) { + $sql = "SELECT * FROM users WHERE user_name = ?;"; + $stmt = mysqli_stmt_init($dbc); + + if (!mysqli_stmt_prepare($stmt, $sql)) { + die("Error: " . mysqli_error($dbc)); + } + + mysqli_stmt_bind_param($stmt, "s", $user_name); + mysqli_stmt_execute($stmt); + + $result = mysqli_stmt_get_result($stmt); + + if ($row = mysqli_fetch_assoc($result)) { + return $row; + } else { + $result = false; + return $result; + } + + mysqli_stmt_close($stmt); } if ($_SERVER['REQUEST_METHOD'] == 'POST') { @@ -31,17 +48,30 @@ if ($_SERVER['REQUEST_METHOD'] == 'POST') { if (empty($_POST['user_name'])) { $errors[] = "You must provide a username."; } else { - $user_name = validate($_POST['user_name']); + $user_name = $_POST['user_name']; + if (!preg_match("/^[a-zA-Z0-9_]*$/", $user_name)) { + $errors[] = "Username can only contain letters, numbers and underscores."; + } + if (strlen($user_name) > 30) { $errors[] = "Your username must be 30 characters or less."; } + + if (username_exists($dbc, $user_name) !== false) { + $errors[] = "The username '" . $user_name . "' has already been taken by another user."; + } } if (empty($_POST['user_pass'])) { $errors[] = "You must provide a password."; } else { - $user_pass = validate($_POST['user_pass']); - $pass_check = validate($_POST['user_pass_check']); + $user_pass = $_POST['user_pass']; + $pass_check = $_POST['user_pass_check']; + + if (preg_match("/^[a-zA-Z0-9\W]*$/", $user_name) === false) { + $errors[] = "Password contains invalid characters!"; + } + if ($user_pass !== $pass_check) { $errors[] = "The two passwords do not match."; } |