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);
?>

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>

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");
}
?>

prepare(“INSERT INTO profile(FULLNAME, EMAIL, USERNAME, PASSWORD CPASSWORD) VALUES(?, ?, ?, ?)”); //Fetching all the records with input credentials $stmt->bind_param(“ssss”, $inFullname, $inEmail, $inUsername, $encryptPassword,$encryptCPassword); //Where s indicates string type. You can use i-integer, d-double $stmt->execute(); $result = $stmt->affected_rows; $stmt -> close(); $db -> close(); if($result > 0) { header(“location: RegSuccess.php”); // user will be taken to the success page } else { echo “Oops. Something went wrong. Please try again”; ?> Try Login
how can i resolve this problem sir…
Hi Ravi,
Don’t know if this is happening with anyone else, but the Login.php page will not redirect to the UserProfile.php unless the HTML sections are removed. I removed the HTML tags and that did the trick. I found the fix here at https://stackoverflow.com/questions/8028957/how-to-fix-headers-already-sent-error-in-php.
Hope this helps anyone that ends up with a white page after submitting the LoginForm.php.
That being said, thank you for this code.. saved me lots of work.
-Jose
Thanks Jose. It is useful information.
I am glad it helped you.
Sir,
I had already entered the data by mysql query, by not creating any registration file. But still to check whether the data is getting inserted or not, I created a registration file.But the same problem is happening with this too. The ‘register.php’ page has been showing as blank.
Sir, is there any alternative option for this section?
$stmt= $db->prepare(“SELECT USERNAME, PASSWORD FROM PROFILE WHERE USERNAME = ?”); //Fetching all the records with input credentials
$stmt->bind_param(“s”, $inUsername); //You need to specify values to each ‘?’ explicitly while using prepared statements
$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 decrpted 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”;
?>
Login
<?php
}
Shreya,
You can replace the line
if ($stmt->fetch() && password_verify($inPassword, $PasswordDB))withif($stmt->fetch())and test.If that works, then try
if($stmt->fetch() && $inPassword=$PasswordDB).You can type
echo "Password = " . $PasswordDB;and check what value is returned.—————————————————
Your register.php is not working fine hence you are not being taken to the next level. Hope you are executing this in WAMP environment.
i am getting eroor in line 20 why ?
Line 20 of Login.php?
It’s the following line.
$stmt= $db->prepare("SELECT USERNAME, PASSWORD FROM PROFILE WHERE USERNAME = ?");The reason could be your table. Did you create the table PROFILE with the same column names?
hey shreya
im facing same problem….have you find the solution?
Comments are closed.