PROGRAMS

PHP Login Form using MySQL

Here you will learn how to develop PHP login form using MySQL database. Have you ever wondered? what happens when you submit your credentials to any login form. You will understand the login application how it actually works in real time here. This PHP login application uses MySQL database to store user information and all the input parameters are validated with javascript. Comments have been added for easy understanding, especially to help newbies. You are always welcome with your doubts. If you are looking for the registration example, follow this link. The Complete Login and Registration Application using PHP can be found here.

This PHP login form using MySQL database connections contains PHP 7.0 methods only. Many methods like mysql_real_escape_string(), mysql_query(), mysql_num_rows(), mysql_connect(), mysql_select_db(), mysql_close() were deprecated in PHP 5 and removed from the latest version of PHP i.e. PHP 7.0. It uses prepared statements and

It uses prepared statements while querying in the database. Since the database contains the encrypted password we have decrypted the password using the method password_verify() while comparing it with the user password. 

To execute PHP programs you would need a localhost server that supports PHP like wamp server or xampp server or any other. Most of them are available freely on the internet. You can click on the respective link and download them.

This is how the Login page looks on the browser (except PHP logo)

Recommended Programs:

LoginForm.php

<html>
<head>
<title>LoginForm.php</title>
<!-- Using external stylesheet to make the registration form look attractive -->
<link rel = "stylesheet" type = "text/css" href="Style.css"/>
<!-- Javascript validation for user inputs -->
<script type="text/javascript">
 function validate()
 {
 var username = document.login.username.value;
 var password = document.login.password.value;

 if (username==null || username=="")
 {
   alert("Username can't be blank");
   return false;
 }
 else if (password==null || password=="")
 {
   alert("password can't be blank");
   return false;
 }
 }
</script>
</head>
<body>

<!-- Make a note that the method type used is post, action page is Login.php and validate() function will get called on submit -->
<div style="text-align:center"><h1>PHP Login Form using MySQL</h1></div>
<br>
 <form name="login" method="post" action="Login.php" onsubmit="return validate();" >
 <div>Username: <input type="text" name="username" /> </div>
 <div>Password: <input type="password" name="password" /> </div>
 <div><input type="submit" value="Login"></input> <input type="reset" value="Reset"></input></div>
</form>
</body>
</html>

Style.css

/* Sample CSS - Modify it as per your taste */ input[type=text], input[type=password] {
 background-color: #EEEEEE;
 border: none;
 color: black;
 width:auto;
 padding: 8px 52px;
 text-decoration: none;
 margin: 4px 2px;
 cursor: pointer;
}

input[type=button], input[type=submit], input[type=reset] {
 background-color: #4CAF50;
 border: none;
 color: white;
 padding: 16px 32px;
 text-decoration: none;
 margin: 4px 2px;
 cursor: pointer;
 }

body{ 
 text-align:right;
 margin: 50px 400px;
}

Once you click on the submit button of the LoginForm.php the request is forwarded to the URL given in the action=”” attribute of the form. In this case, it is forwarded to the Login.php

Login.php
<html>
<body>
<?php 
 include_once("DBConnection.php"); 
 session_start(); //always start a session in the beginning 
if ($_SERVER['REQUEST_METHOD'] == 'POST') 
{ 
 if (empty($_POST['username']) || empty($_POST['password'])) //Validating inputs using PHP code 
 { 
  echo 
  "Incorrect username or password"; //
  header("location: LoginForm.php");//You will be sent to Login.php for re-login 
 } 

  $inUsername = $_POST["username"]; // as the method type in the form is "post" we are using $_POST otherwise it would be $_GET[] 
  $inPassword = $_POST["password"]; 
  $stmt= $db->prepare("SELECT USERNAME, PASSWORD FROM PROFILE WHERE USERNAME = ?"); //Fetching all the records with input credentials
  $stmt->bind_param("s", $inUsername); //bind_param() - Binds variables to a prepared statement as parameters. "s" indicates the type of the parameter.
  $stmt->execute();
  $stmt->bind_result($UsernameDB, $PasswordDB); // Binding i.e. mapping database results to new variables
   
 //Compare if the database has username and password entered by the user. Password has to be decrypted while comparing.
  if ($stmt->fetch() && password_verify($inPassword, $PasswordDB)) 
  {
  $_SESSION['username']=$inUsername; //Storing the username value in session variable so that it can be retrieved on other pages
  header("location: UserProfile.php"); // user will be taken to profile page
  }
  else
  {
     echo "Incorrect username or password"; 
    ?>   
    <a href="LoginForm.php">Login</a>
       <?php 
  } 
} 
       ?>
</body> 
</html>

DBConnection.php
This code is used to establish a connection with the MySQL database server.
As a best practice maintain database connections in a separate file so that any changes to the database server can be done quickly.

<?php 
 define('DB_SERVER', 'localhost:3306'); //database server url and port
 define('DB_USERNAME', 'root');  //database server username
 define('DB_PASSWORD', 'root123'); //database server password
 define('DB_DATABASE', 'profile'); //where profile is the database 
 
 $db = mysqli_connect(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_DATABASE); 
?>

MySQL scripts used in the PHP login application

UserProfile.php

<html>
<title>userProfile.php</title>
<body>
 <?php
  session_start();
  $username = $_SESSION['username']; //retrieve the session variable
 ?>
 
 <div style="text-align:center"><h1>User Profile</h1></div>
 <br/>

 <div style="font-weight:bold"> Welcome <?php echo $username ?> </div>
  
 <div style="text-align: right"><a href="Logout.php">Logout</a></div> <!-- calling Logout.php to destroy the session -->
 
 <?php
 if(!isset($_SESSION['username'])) //If user is not logged in then he cannot access the profile page
 {
  //echo 'You are not logged in. <a href="login.php">Click here</a> to log in.';
  header("location:LoginForm.php");
 }
 ?>
</body>
</html>

User Profile page
Logout.php
<?php 
 
 session_start();
 $username = $_SESSION['username']; //retrieve the session variable

 unset($_SESSION['username']); //to remove session variable
 session_destroy(); //destroy the session
 header("location: LoginForm.php"); //to redirect back to "Login.php" after logging out
 exit();

 if(!isset($_SESSION['username'])) //If user is not logged in then he cannot access the profile page
 {
 //echo 'You are not logged in. <a href="login.php">Click here</a> to log in.';
 header("location:LoginForm.php");
 }
?>
Ravi Bandakkanavar

A Techie, Blogger, Web Designer, Programmer by passion who aspires to learn new Technologies every day. A founder of Krazytech. It's been 10+ years since I am publishing articles and enjoying every bit of it. I want to share the knowledge and build a great community with people like you.

Leave a Comment

View Comments

  • Hello Sir
    I am getting error as Warning: mysqli_connect(): (HY000/1045): Access denied for user 'root'@'localhost' (using password: YES) in C:\xampp\htdocs\essenet\dbconnection.php on line 7 while trying to login using registered credential in mysql, please suggest

  • working with xampp environment, when the sign in form is click to sign in it shows my php code(" . $passwordError . ""; ?> " . $noValid . ""; ?>) on below the enter password. And when i click on sign up it also show my php code on email box() and name box it shows (). kindly help. Thanks

    • Abiodun,

      Do you have access to the Database server? Could you please login and check whether the registered user details are present in the database?
      I hope you have configured the correct database user details in the connection file.

    • Hi
      By default, it will be root or no username in some cases. You need to set the username manually in such cases.
      For MySQL the default port is 3306. During installation, you get an option to update it even.
      You can check all the configuration details in conf file.

  • Notice: Undefined variable: db in C:\xampp\htdocs\OPTRA\login.php on line 18

    Fatal error: Call to a member function prepare() on null in C:\xampp\htdocs\OPTRA\login.php on line 18

      • Hi Ravi, I can't read your full comments since it's always loading. Could you send this comment to my email? I met the same issue.

        • Hi Zeyu,

          Are you seeing this error?

          Notice: Undefined variable: db in C:\xampp\htdocs\OPTRA\login.php on line 18

          Fatal error: Call to a member function prepare() on null in C:\xampp\htdocs\OPTRA\login.php on line 18

          It is something to do with the database query. You should verify whether the table is created and column names are correctly used in the query.

  • Yes I created a table 'PROFILE' and insterted USERNAME as 'wycliff' and PASSWORD as '1234' and I am runing it in a xampp environment. It still gives me the errors

1 2 3 5
Share
Published by
Ravi Bandakkanavar

Recent Posts

Everything You Need To Know About Create React App

The configuration of resources can be a time-consuming and difficult operation while creating a React…

3 weeks ago

Causes of CyberCrime and Preventive Measures

          Rapid technological growth and developments have provided vast areas of…

4 weeks ago

How Data Lineage will Improve Business Practices

How often have you thought about changing the way that you store and use data?…

4 weeks ago

10 Dominating Programming Language for Mobile App In 2022

Programming Languages are a set of rules that aid in transforming a concept into a…

1 month ago

What is Serverless Edge Computing? Features | Benefits

Serverless edge computing is a new technology with a lot of promise, but it can…

1 month ago

Are Your Accounts Protected Against Cyberattacks?

Do any of your passwords include personal names, date of birth, or pet names? If…

2 months ago