summaryrefslogtreecommitdiff
path: root/signin.php
blob: e559614c7367f79159369ace2b5ecd74318bdf97 (plain)
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
<?php session_start()?>
<!DOCTYPE html>
<html>
<head>
	<title>Sign in - cflip.net forum</title>
	<link rel="stylesheet" href="styles/style.css">
</head>
<body>
	<?php include_once 'templates/header.php'?>
	<h2>Sign in</h2>
	<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post">
		<label for="user_name">Username: </label><br>
		<input type="text" name="user_name"><br>
		<label for="user_pass">Password: </label><br>
		<input type="password" name="user_pass"><br>
		<input type="submit" name="submit">
	</form>

<?php

include_once 'includes/db_inc.php';

function validate($data)  {
	$data = trim($data);
	$data = stripslashes($data);
	$data = htmlspecialchars($data);
	return $data;
}

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
	$errors = array();
	
	if (empty($_POST['user_name'])) {
		$errors[] = 'Please provide a username.';
	} else {
		$user_name = validate($_POST['user_name']);
	}

	if (empty($_POST['user_pass'])) {
		$errors[] = 'Please provide a password.';
	} else {
		$user_pass = $_POST['user_pass'];
	}

	if (!empty($errors)) {
		echo 'Please check the following problems: <ul>';
		foreach ($errors as $err) {
			echo '<li>' . $err . '</li>';
		}
		echo '</ul>';
	} else {
		$sql = "SELECT user_id, user_name, user_pass FROM users WHERE user_name = '" . $user_name . "';";
		$result = mysqli_query($dbc, $sql);

		if (!$result) {
			echo 'An error occurred while signing in: ' . mysqli_error($dbc);
		} else {
			if (mysqli_num_rows($result) == 0) {
				echo 'There is no user with that name. Did you mean to <a href="register.php">create a new account?</a>';
			} else {
				while ($row = mysqli_fetch_assoc($result)) {
					if (!password_verify($user_pass, $row['user_pass'])) {
						echo 'Password does not match!';
					} else {
						$_SESSION['signed_in'] = true;
						$_SESSION['user_id'] = $row['user_id'];
						$_SESSION['user_name'] = $row['user_name'];

						header("Location: index.php");
					}
				}
			}
		}
	}
}
?>
</body>
</html>