I am working on a basic login system that allows registration / sign in storing users in a MySQL database. I have it so people can register, it stores the username and a hashed password in the DB. When someone logs in, it shows a success message or an error message depending on if the username and password matched up.
My problem lies in the login function. I need to create the user session and redirect them to the logged-in only section of the site, instead of displaying the success message that is currently there. I'm unsure of how to do that...
Here is my code:
Login / Register Functions
function login($username, $password) {
$userpass = sha1($password);
$result = mysqli_query($con, "SELECT * FROM members WHERE username='$username' AND password='$userpass'");
while($row = mysqli_fetch_array($result)) {
$success = true;
}
if($success == true) {
echo 'Success!';
} else {
echo '<div class="alert alert-danger">Oops! It looks like your username and/or password are incorrect. Please try again.</div>';
}
} // END LOGIN FUNCTION
function register($username, $password) {
$userpass = sha1($password);
// Check if Username Exists
$result = mysqli_query($con,"SELECT * FROM members WHERE username='$username'");
while($row = mysqli_fetch_array($result)) {
$userexist = 1;
}
if($userexist > 0) {
echo '<div class="alert alert-danger">Sorry, it looks like that username is already taken.</div>';
} else {
$newmember = "INSERT INTO members SET username='$username', password='$userpass'";
if(mysqli_query($con,$newmember)) {
echo '<div class="alert alert-success">Congrats! You can now log in using your username and password</div>';
}
}
}
think like this
function login($username, $password) {
$userpass = sha1($password);
$result = mysqli_query($con, "SELECT * FROM members WHERE username='$username' AND password='$userpass'");
while($row = mysqli_fetch_array($result)) {
$success = true;
}
if($success == true) {
$_SESSION['username']= $username;
//redirect to home page
} else {
echo '<div class="alert alert-danger">Oops! It looks like your username and/or password are incorrect. Please try again.</div>';
}
} // END LOGIN FUNCTION