PHP User Login Form with MySQL Database
This post will show you how to create A User login Form using PHP & MySQL
Before Creating a User Login Form you may need to Create a User Registration Form
How to create a User Registration Form Here
Prior to that you need to complete the items listed Below
- Mamp or xampp with phpMyAdmin install into your Computer , check out here
- A Sample Database created Check out Here
- New User Created . Check out Here
- A New table created , check out Here
- Insert Data into the Table Here
<?php $visitnumber=0; // Initialize the session session_start(); // Check if the user is already logged in, if yes then redirect him to welcome page if(isset($_SESSION["loggedin"]) && $_SESSION["loggedin"] === true){ header("location: welcome.php"); exit; } // Include config file include ("C:/xampp/htdocs/dbconnection.php"); // Define variables and initialize with empty values $username = $password = ""; $username_err = $password_err = ""; // Processing form data when form is submitted // Which request method was used to access the page; e.g. 'GET', 'HEAD', 'POST', 'PUT'. if($_SERVER["REQUEST_METHOD"] == "POST"){ // Check if username is empty if(empty(trim($_POST["username"]))){ $username_err = "Please enter username."; } else{ // If Not Empty get the enter username $username = trim($_POST["username"]); } // Check if password is empty if(empty(trim($_POST["password"]))){ $password_err = "Please enter your password."; } else{ // If Not Empty get the enter Password $password = trim($_POST["password"]); } // Validate credentials // If Both Input Username & Password being Enter if(empty($username_err) && empty($password_err)){ // Prepare a select statement $sql = "SELECT id, username, password FROM users WHERE username = ?"; //(1) Prepare the statement : Return Bool if($stmt = $dbConnectionStatus->prepare($sql)){ // (2) Bind variables to the prepared statement as parameters $stmt->bind_param('s',$param_username); // (3) Set parameters $param_username = $username; // Attempt to execute the prepared statement if($stmt->execute()){ // Store result $stmt->store_result(); // Check if username exists, if yes then verify password if($stmt->num_rows == 1){ // Bind result variables $stmt->bind_result($id, $username, $hashed_password); if($stmt->fetch()){ // Verify Passwords if(password_verify($password, $hashed_password)){ // Password is correct, so start a new session session_start(); // Store data in session variables // Declare Session Login == true (An associative array containing session variables available to the current script) $_SESSION["loggedin"] = true; $_SESSION["id"] = $id; $_SESSION["username"] = $username; // Login Time Stamp $time =strtotime("now"); $_SESSION['last_login_timestamp'] = $time; // Cookies to Login and Log Out Users setcookie("loginAuthorised","loginAuthorised",time()+30,"/"); // Redirect user to welcome page header("location: welcomes.php"); } else{ // Display an error message if password is not valid $password_err = "The password you entered was not valid."; } } } else{ // Display an error message if username doesn't exist $username_err = "No account found with that username."; } } else{ echo "Oops! Something went wrong. Please try again later."; } // Close statement mysqli_stmt_close($stmt); } } // Close connection mysqli_close($dbConnectionStatus); } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Login</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.css"> <style type="text/css"> body{ font: 14px sans-serif; } .wrapper{ width: 350px; padding: 20px; } </style> </head> <body> <div class="wrapper"> <h2>Login</h2> <p> Your credentials to login.</p> <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post"> <div class="form-group <?php echo (!empty($username_err)) ? 'has-error' : ''; ?>"> <label>Username</label> <input type="text" name="username" class="form-control" value="<?php echo $username; ?>"> <span class="help-block"><?php echo $username_err; ?></span> </div> <div class="form-group <?php echo (!empty($password_err)) ? 'has-error' : ''; ?>"> <label>Password</label> <input type="password" name="password" class="form-control"> <span class="help-block"><?php echo $password_err; ?></span> </div> <div class="form-group"> <input type="submit" class="btn btn-primary" value="Login"> </div> <p>Don't have an account? <a href="registers.php">Sign Up Now</a>.</p> </form> </div> </body> </html>
Redirect to Welcome Page When User Successfully Login
User Welcome Page
The Welcom Page Implement Cookie
<?php $visitnumber=0; $lastVisitID =0; $logedIn = false; // Equivalent to 1 Day Tracking Time $trackingtime = 86400; // Initialize the session session_start(); // Check if the user is logged in, if not then redirect him to login page if(!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true){ header("location: logins.php"); exit; } // else , If the User is Logined else{ echo strtotime("now"), "\n"; echo $_SESSION["last_login_timestamp"]; // Time Now - Previous Time Login Session // If current Time Minus Login Time More than 20 seconds if((strtotime("now") - $_SESSION["last_login_timestamp"]) > 20) { // Log the User Out header("location:logouts.php"); // Assign logedIn == False $logedIn = false; } // Assiigned LogIn == True else{ $logedIn = true;} } // Refresh welcomes.php Page after 21 Seconds to update the Current Time Value $page = $_SERVER['PHP_SELF']; $sec = "21"; header("Refresh: $sec; url=welcomes.php"); //------------------------------------------------------------------------------- //------------------------------------------------------------------------------- if(isset($_COOKIE['userlogedin'])){ // Get the Cookie Value $visitnumber= $_COOKIE['userlogedin']; $visitnumber++; } if(isset($_COOKIE['$lastvisittime'])){ $lastvisittime=$_COOKIE['$lastvisittime']; } // Insert Cookies // Parameter ->name of the Cookie ,Value of the Cookie , Time to expired setcookie('userlogedin',$visitnumber,time()+$trackingtime); setcookie('$lastvisittime',date("d-m-y H:i:s"),time()+86400); if(!$visitnumber){ echo 'Welcome To your First Visit'; } else{ echo'You have been visit number of '.$visitnumber.' time before at '.$lastvisittime.'<br>'; } ?> <!DOCTYPE html> <html lang="en"> <!--IF logIn == true Display the HTML Code---> <?php if($logedIn) { ?> <head> <meta charset="UTF-8"> <!--Bootstrap Link --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script> <!--This Link Enable Mobile Menu Drop Down--> <script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script> <!--Font Awesome CDN Link --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous"> <style type="text/css"> body{ font: 14px sans-serif; text-align: center; } </style> </head> <body> <!--- ----------------------------------------------------------------------------------------------------------------------> <!--nav class="navbar navbar-dark bg-dark"--> <nav class="navbar navbar-expand-lg navbar-dark bg-dark"> <a class="navbar-brand">CreatifWerks</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContents" aria-controls="navbarSupportedContents" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContents"> <ul class="navbar-nav ml-auto"> <li class="nav-item active"> <a class="nav-link" href="https://www.creatifwerks.com/">Home <span class="sr-only">(current)</span></a> </li> <li class="nav-item"> <a class="nav-link" href="https://www.creatifwerks.com/blog/">Blog</a> </li> <li class="nav-item"> <a class="nav-link" href="https://www.creatifwerks.com/tools-and-calculator-in-singapore/">Tools</a> </li> <li class="nav-item"> <a class="nav-link" href=" https://www.creatifwerks.com/charts/">Charts</a> </li> <li class="nav-item"> <a class="nav-link" href="https://www.creatifwerks.com/game-development-in-singapore/">Game</a> </li> <li class="nav-item"> <a class="nav-link" href="https://www.creatifwerks.com/the-author/">About Me</a> </li> <li class="nav-item"> <a class="nav-link" href="https://www.creatifwerks.com/contact/">Contact</a> </li> </ul> <!-------------This Portion Will display the User / Login Status / Change Passwords-------------------> <ul class="navbar-nav ml-auto nav-flex-icons"> <li class="nav-item"> <a href="reset-passwords.php"class="fa fa-user" aria-hidden="true" style="font-size:25px"data-toggle="tooltip" data-placement="bottom" title=<?php echo htmlspecialchars($_SESSION["username"]); ?>></a> </li> <li class="nav-item"> <a href="reset-passwords.php"class="fa fa-key" aria-hidden="true" style="font-size:25px; margin-left:10px;"data-toggle="tooltip" data-placement="bottom" title="Reset Password"></a> </li> <li class="nav-item"> <a href="logouts.php"><i class="fa fa-sign-out" style="font-size:25px; margin-left:10px;" data-toggle="tooltip" data-placement="bottom" title="Sign Out"></i></a> </li> </ul> <!---------------------------------------------------------------------------------------------------> </div> </nav> <!--- --------------------------------------------------------Greet the User------------------------------------------------------------> <div class="page-header"> <!---------This Section will display the User Name------------> <h1>Hi, <b><?php echo htmlspecialchars($_SESSION["username"]); ?></b>. Welcome to Creatifwerks.com.</h1> </div> <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script> </body> <?php } ?> </html>
Sign-Out
<?php // Initialize the session session_start(); // Unset all of the session variables $_SESSION = array(); // Destroy the session. session_destroy(); // Redirect to login page header("location: login.php"); exit; ?>
Reset User Password
<?php // Initialize the session session_start(); // Check if the user is logged in, otherwise redirect to login page if(!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true){ header("location: login.php"); exit; } // Include config file include ("C:/xampp/htdocs/dbconnection.php"); // Define variables and initialize with empty values $new_password = $confirm_password = ""; $new_password_err = $confirm_password_err = ""; // Processing form data when form is submitted // Which request method was used to access the page; e.g. 'GET', 'HEAD', 'POST', 'PUT'. if($_SERVER["REQUEST_METHOD"] == "POST"){ // Validate new password if(empty(trim($_POST["new_password"]))){ $new_password_err = "Please enter the new password."; } elseif(strlen(trim($_POST["new_password"])) < 6){ $new_password_err = "Password must have at least 6 characters."; } else{ // Get the New Password $new_password = trim($_POST["new_password"]); } // Validate confirm password if(empty(trim($_POST["confirm_password"]))){ $confirm_password_err = "Please confirm the password."; } else{ // Get User Inputted Confirm Password $confirm_password = trim($_POST["confirm_password"]); // If Password did not matched if(empty($new_password_err) && ($new_password != $confirm_password)){ $confirm_password_err = "Password did not match."; } } // Check input errors before updating the database with new Password if(empty($new_password_err) && empty($confirm_password_err)){ // (1) Prepare an update Password statement // Set Password of the Specific User id $sql = "UPDATE users SET password = ? WHERE id = ?"; // Check Whether the Prepare statement execute Successful : Return Bool if($stmt = $dbConnectionStatus ->prepare($sql)){ // (2) Bind variables to the prepared statement as parameters mysqli_stmt_bind_param($stmt, "si", $param_password, $param_id); $stmt->bind_param('si', $param_password, $param_id); // (3) Set parameters $param_password = password_hash($new_password, PASSWORD_DEFAULT); //(4) Get the User Id by Refering to the Session id $param_id = $_SESSION["id"]; // Attempt to execute the prepared statement if( $stmt->execute()){ // Password updated successfully. Destroy the session, and redirect to login page session_destroy(); header("location: logins.php"); exit(); } else{ echo "Oops! Something went wrong. Please try again later."; } // Close statement mysqli_stmt_close($stmt); } } // Close connection mysqli_close($dbConnectionStatus); } ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Reset Password</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.css"> <style type="text/css"> body{ font: 14px sans-serif; } .wrapper{ width: 350px; padding: 20px; } </style> </head> <body> <div class="wrapper"> <h2>Reset Password</h2> <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post"> <div class="form-group <?php echo (!empty($new_password_err)) ? 'has-error' : ''; ?>"> <label>New Password</label> <input type="password" name="new_password" class="form-control" value="<?php echo $new_password; ?>"> <span class="help-block"><?php echo $new_password_err; ?></span> </div> <div class="form-group <?php echo (!empty($confirm_password_err)) ? 'has-error' : ''; ?>"> <label>Confirm Password</label> <input type="password" name="confirm_password" class="form-control"> <span class="help-block"><?php echo $confirm_password_err; ?></span> </div> <div class="form-group"> <input type="submit" class="btn btn-primary" value="Submit"> <a class="btn btn-link" href="welcome.php">Cancel</a> </div> </form> </div> </body> </html>
Leave a Reply