server.php - VirajKanse/Student_Authentication GitHub Wiki
Open "server.php" in sublime and paste this code in it :point_down: :point_down: :
<?php
session_start();
// variable declaration
$stud = "";
$rl = "";
$errors = array();
$_SESSION['success'] = "";
// connect to database
$db = mysqli_connect('localhost', 'root', '', 'registration');
// REGISTER USER
if (isset($_POST['reg_user'])) {
// receive all input values from the form
$stud = mysqli_real_escape_string($db, $_POST['stud']);
$rl = mysqli_real_escape_string($db, $_POST['rl']);
$enr_1 = mysqli_real_escape_string($db, $_POST['enr_1']);
$enr_2 = mysqli_real_escape_string($db, $_POST['enr_2']);
// form validation: ensure that the form is correctly filled
if (empty($stud)) { array_push($errors, "stud is required"); }
if (empty($rl)) { array_push($errors, "rl is required"); }
if (empty($enr_1)) { array_push($errors, "enr is required"); }
if ($enr_1 != $enr_2) {
array_push($errors, "The two enrs do not match");
}
// register user if there are no errors in the form
if (count($errors) == 0) {
$enr = md5($enr_1);//encrypt the enr before saving in the database
$query = "INSERT INTO users (stud, rl, enr)
VALUES('$stud', '$rl', '$enr')";
mysqli_query($db, $query);
$_SESSION['stud'] = $stud;
$_SESSION['success'] = "You are now logged in";
header('location: index.php');
}
}
// ...
Sessions are used to track logged in users and so we include a session_start() at the top of the file.
The comments in the code pretty much explain everything, but I'll highlight a few things here.
The if statement determines if the reg_user button on the registration form is clicked. Remember, in our form, the submit button has a name attribute set to reg_user and that is what we are referencing in the if statement.
All the data is received from the form and checked to make sure that the user correctly filled the form. Passwords are also compared to make sure they match.