-
Notifications
You must be signed in to change notification settings - Fork 1
/
insert.php
84 lines (71 loc) · 2.54 KB
/
insert.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
<?php
// Redirecting to registration page for GET requests
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
return header('Location: /register.php');
}
// Starting session
if (session_status() === PHP_SESSION_NONE) {
session_start();
}
// Validating role
if (empty(trim($_POST['role']))) {
$_SESSION['error']['role'] = 'Role cannot be empty!';
} elseif (trim($_POST['role']) !== 'admin' && trim($_POST['role']) !== 'manager') {
$_SESSION['error']['role'] = 'Role is invalid!';
}
// Validating email
if (empty(trim($_POST['email']))) {
$_SESSION['error']['email'] = 'Email cannot be empty!';
} elseif (empty(filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL))) {
$_SESSION['error']['email'] = 'Email seems invalid!';
}
// Validating password
if (empty(trim($_POST['password']))) {
$_SESSION['error']['password'] = 'Password cannot be empty!';
} elseif (
empty(trim($_POST['password2'])) ||
trim($_POST['password2'] !== trim($_POST['password']))
) {
$_SESSION['error']['password'] = 'Passwords do not match!';
}
// Redirecting to registration page to display errors
if (isset($_SESSION['error'])) {
$_SESSION['input'] = [
'role' => $_POST['role'],
'email' => $_POST['email'],
];
return header('Location: /register.php');
}
// Sanitizing data
$role = filter_input(INPUT_POST, 'role', FILTER_SANITIZE_STRING);
$email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_EMAIL);
$password = filter_input(INPUT_POST, 'password', FILTER_SANITIZE_STRING);
/** @var Database */
$db = require_once './helpers/Database.php';
$conn = $db->getConnection();
// Checking for existing user
$stmt = $conn->prepare('SELECT id FROM `users` WHERE `email` = :email LIMIT 1');
$stmt->bindParam(':email', $email);
$stmt->execute();
$user = $stmt->fetch();
if (!empty($user)) {
$_SESSION['error']['email'] = 'Email is already registered!';
$_SESSION['input'] = [
'role' => $_POST['role'],
'email' => $_POST['email'],
];
return header('Location: /register.php');
}
// Hashing password
$password = password_hash($password, PASSWORD_DEFAULT);
// Inserting new user into database
$stmt = $conn->prepare(
'INSERT INTO `users` (`email`, `password`, `role`) VALUES (:email, :password, :role)'
);
$stmt->bindParam(':email', $email);
$stmt->bindParam(':password', $password);
$stmt->bindParam(':role', $role);
$stmt->execute();
// Redirecting to login page to display confirmation of registration
$_SESSION['flash']['success'] = 'Registration is successful! Please login.';
return header('Location: /login.php');