/
login.php
94 lines (64 loc) · 2.07 KB
/
login.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
85
86
87
88
89
90
91
92
93
94
<?php
//HTTPS redirect
// if ($_SERVER['HTTPS'] !== 'on') {
// $redirectURL = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
// header("Location: $redirectURL");
// exit;
// }
// print_r($_POST);
// print $_POST['username'];
if(!session_start()) {
// If the session couldn't start, present an error
header("Location: error.php");
exit;
}
// Check to see if the user has already logged in
$loggedIn = empty($_SESSION['loggedin']) ? false : $_SESSION['loggedin'];
if ($loggedIn) {
header("Location: home.php");
exit;
}
$action = empty($_POST['action']) ? '' : $_POST['action'];
if($action == "do_login"){
handle_login();
}else{
login_form();
}
function handle_login(){
$username = $_POST['username'];
$password = $_POST['password'];
require_once 'db.conf';
$mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
if($mysqli->connect_error){
$error = 'Error: ' . $mysqli->connect_errno . ' ' . $mysqli->connect_error;
require "login_form.php";
exit;
}
$username = $mysqli->real_escape_string($username);
$password = $mysqli->real_escape_string($password);
$query = "SELECT * FROM users WHERE username = '$username' AND password = '$password'";
$mysqliResult = $mysqli->query($query);
// print_r(mysqli_fetch_all($mysqliResult,MYSQLI_ASSOC));
if($mysqliResult){
$match = $mysqliResult->num_rows;
$mysqliResult->close();
$mysqli->close();
//print "The match is $match";
if($match == 1){
$_SESSION['loggedin'] = $username;
header("Location: home.php");
exit;
}else{
$error = "Incorrect username or password";
require "login_form.php";
exit;
}
}
}
function login_form(){
$error = "";
$username = "";
require "login_form.php";
exit;
}
?>