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

Hai ravi,
I need to login and display exsits if password and username is correct in db. Kindly help pls i am new to php
0)
{
echo “Exists”;
}
else
echo “Doesn’t exist”;
}
}
?>
Hi Prem,
You can use the same code as is and replace the following lines in Login.php with echo statements.
if ($stmt->fetch() && password_verify($inPassword, $PasswordDB))
{
echo “Exists”;
}
else
{
}
Thanx sir,
I have tried another code and its working.
Kindly support in my future coding also as i am a beginner
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?
hello sir,
my login.php page has been showing incorrect username and password even if I login with the correct username and password mentioned in the database. Can you help with this?
Hi Shreya,
Hope you have used the same methods as specified in the article to encrypt and decrypt the password.
You can verify your records in the database.
Go through the following example to know how to encrypt your password:
https://krazytech.com/programs/php-mysql-registration-form
Hi Ravi,
Thank you very much for your excellent tutorial. I’m running it on a Raspberry Pi 3.
There is just one little error in the “Logout.php” file.
The line “mysql_close($connection);” should be “mysql_close($connection);”
because the older function was depreciated from PHP 7.
sorry that should be “mysqli_close($connection);”
Hi Nick,
Thanks for pointing it out. Sorry about that.
I corrected it. Take a look now.
Since we are storing the database connection object in the variable $db, we should use the variable $db while closing a connection and it should be done at two places.
1.Login.php
2.Logout.php
$db = mysqli_connect(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_DATABASE);.
.
mysqli_close($db);
hello sir, i need to make a website with login page.which type of validation should be best for me ?i have tried js validation but at the background in the pagesource somebody might find my id and password.please help me sir.
Hi Aloka,
Yes. Using javascript would expose your values. You can overcome this by using database validation.
I have mentioned following chunk of code in Login.php.
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
if (empty($_POST['username']) || empty($_POST['password'])) //This is the way to validate inputs using PHP code but here we are using javascript validations so it is not necessary
{
echo "Please enter the correct Username and Password";
//header("location: LoginForm.php");//You will be sent to Login.php for re-login
}
The database validation would consume little more time as compared to JS validations but in the case of JS, it would increase the web page size. You need to choose based on your requirement.
If you still want to go for Javascript validations, you can use document.getElementById() to read from fields and have the code at a separate place by giving a reference in the head.
My suggestion to you: go for certain frameworks which will reduce a lot of your work. some famous ones are https://laravel.com/, https://cakephp.org/ etc.
Keep us updated with what you choose and about your website and Good Luck :)
Updated the Login application with PHP 7.0 supported methods as many methods like mysql_real_escape_string(), mysql_query(), mysql_num_rows(), mysql_connect(), mysql_select_db(), mysql_close() were depricated in PHP 5 and removed from the latest version of PHP i.e. PHP 7.0.
Hi Sir,
How to run php in xamp. How to connect html and sql for online library renewal system for mini project.
Hi Sangavi,
Please go through following post to understand on html or php files location and also to create SQL database.
Xamp and wamp both are almost same.
can you give me an idea for my mini project so that it will be helpful for my career.
Hi Dinesh,
Do you want mini projects using PHP ?
There are multiple projects which you can do using PHP.
Find some samples here
https://krazytech.com/projects/a-detailed-srs-software-requirements-specification-report-for-e-administration-of-computer-labs-project
https://krazytech.com/projects/computer-science-project-topics
Comments are closed.