PHP Signup with OTP Email Verification System - Login and Logout (Part 5)




Login to Create a Session:

In order to use an active account after the OTP verification and account activation process needs to login into the account, So in this tutorial will create a PHP login function to set a session to login into the account.

Now we will create a PHP login function with validations.

In the index.php file copy the below code and paste it above the signup code.


PHP Login Code:

  • In this code, we have set cookies for remember me PHP function which will create in the next tutorial.

session_start();

if (isset($_SESSION['id'])) {
header("Location: home.php");
}

// LOGIN PROCESS CODE
if (isset($_POST['login'])) {
$email = mysqli_real_escape_string($conn, $_POST['email']);
$password = mysqli_real_escape_string($conn, md5($_POST['password']));

$sqlLogin = "SELECT * FROM user WHERE email ='".$email."' AND password = '".$password."' AND status = 'active'";
$resultLogin = mysqli_query($conn, $sqlLogin);

if (mysqli_num_rows($resultLogin) > 0) {

$rememberme = $_POST['rememberme'];

if ($rememberme == "checked") {
setcookie('email', $email);
setcookie('password', $password);
}
else{
setcookie('email', '');
setcookie('password', '');
}
if($rowLogin = mysqli_fetch_assoc($resultLogin)){

$_SESSION['id'] = $rowLogin['uid'];
$name = $rowLogin['name'];

setcookie('username', $name);

header("Location: home.php");
}else{
echo "<script>alert('Opss something wrong..');</script>";
}
}
else{
echo "<script>alert('No user exist with this email OR wrong password');</script>";
}
}

PHP Logout Code:

  • create a logout.php file and copy-paste the below code.
<?php
include "config.php";
session_start();

if (isset($_SESSION['id'])) {
setcookie('username', "");

if (session_destroy()) {
header("Location: index.php");
}
}

1 Comments

Post a Comment

Post a Comment

Previous Post Next Post