Developing a Login System with PHP and MySQL
Most interactive websites nowadays would require a user to log in into the website’s system in order to provide a customized experience for the user. Once the user has logged in, the website will be able to provide a presentation that is tailored to the user’s preferences.
A basic login system typically contains 3 components:
1. The component that allows a user to register his preferred login id and password
1. The component that allows a user to register his preferred login id and password
2. The component that allows the system to verify and authenticate the user when he subsequently logs in
3. The component that sends the user’s password to his registered email address if the user forgets his password
Such a system can be easily created using PHP and MySQL.
Component 1 – Registration
Component 1 is typically implemented using a simple HTML form that contains 3 fields and 2 buttons:
1. A preferred login id field
2. A preferred password field
3. A valid email address field
4. A Submit button
5. A Reset button
1. A preferred login id field
2. A preferred password field
3. A valid email address field
4. A Submit button
5. A Reset button
Assume that such a form is coded into a file named register.html. The following HTML code excerpt is a typical example. When the user has filled in all the fields, the register.php page is called when the user clicks on the Submit button.
[form name="register" method="post" action="register.php"]
[input name="login id" type="text" value="loginid" size="20"/][br]
[input name="password" type="text" value="password" size="20"/][br]
[input name="email" type="text" value="email" size="50"/][br]
[input type="submit" name="submit" value="submit"/]
[input type="reset" name="reset" value="reset"/]
[/form]
[input name="login id" type="text" value="loginid" size="20"/][br]
[input name="password" type="text" value="password" size="20"/][br]
[input name="email" type="text" value="email" size="50"/][br]
[input type="submit" name="submit" value="submit"/]
[input type="reset" name="reset" value="reset"/]
[/form]
The following code excerpt can be used as part of register.php to process the registration. It connects to the MySQL database and inserts a line of data into the table used to store the registration information.
@mysql_connect("localhost", "mysql_login", "mysql_pwd") or die("Cannot connect to DB!");
@mysql_select_db("tbl_login") or die("Cannot select DB!");
$sql="INSERT INTO login_tbl (loginid, password and email) VALUES (".$loginid.”,”.$password.”,”.$email.”)”;
$r = mysql_query($sql);
if(!$r) {
$err=mysql_error();
print $err;
exit();
}
@mysql_select_db("tbl_login") or die("Cannot select DB!");
$sql="INSERT INTO login_tbl (loginid, password and email) VALUES (".$loginid.”,”.$password.”,”.$email.”)”;
$r = mysql_query($sql);
if(!$r) {
$err=mysql_error();
print $err;
exit();
}
The code excerpt assumes that the MySQL table that is used to store the registration data is named tbl_login and contains 3 fields – the loginid, password and email fields. The values of the $loginid, $password and $email variables are passed in from the form in register.html using the post method.
Component 2 – Verification and Authentication
A registered user will want to log into the system to access the functionality provided by the website. The user will have to provide his login id and password for the system to verify and authenticate.
This is typically done through a simple HTML form. This HTML form typically contains 2 fields and 2 buttons:
1. A login id field
2. A password field
3. A Submit button
4. A Reset button
1. A login id field
2. A password field
3. A Submit button
4. A Reset button
Assume that such a form is coded into a file named authenticate.html. The following HTML code excerpt is a typical example. When the user has filled in all the fields, the authenticate.php page is called when the user clicks on the Submit button.
[form name="authenticate" method="post" action="authenticate.php"]
[input name="login id" type="text" value="loginid" size="20"/][br]
[input name="password" type="text" value="password" size="20"/][br]
[input type="submit" name="submit" value="submit"/]
[input type="reset" name="reset" value="reset"/]
[/form]
[input name="login id" type="text" value="loginid" size="20"/][br]
[input name="password" type="text" value="password" size="20"/][br]
[input type="submit" name="submit" value="submit"/]
[input type="reset" name="reset" value="reset"/]
[/form]
The following code excerpt can be used as part of authenticate.php to process the login request. It connects to the MySQL database and queries the table used to store the registration information.
@mysql_connect("localhost", "mysql_login", "mysql_pwd") or die("Cannot connect to DB!");
@mysql_select_db("tbl_login") or die("Cannot select DB!");
$sql="SELECT loginid FROM login_tbl WHERE loginid=’".$loginid.”’ and password=’”.$password.”’”;
$r = mysql_query($sql);
if(!$r) {
$err=mysql_error();
print $err;
exit();
}
if(mysql_affected_rows()==0){
print "no such login in the system. please try again.";
exit();
}
else{
print "successfully logged into system.";
//proceed to perform website’s functionality – e.g. present information to the user
}
@mysql_select_db("tbl_login") or die("Cannot select DB!");
$sql="SELECT loginid FROM login_tbl WHERE loginid=’".$loginid.”’ and password=’”.$password.”’”;
$r = mysql_query($sql);
if(!$r) {
$err=mysql_error();
print $err;
exit();
}
if(mysql_affected_rows()==0){
print "no such login in the system. please try again.";
exit();
}
else{
print "successfully logged into system.";
//proceed to perform website’s functionality – e.g. present information to the user
}
As in component 1, the code excerpt assumes that the MySQL table that is used to store the registration data is named tbl_login and contains 3 fields – the loginid, password and email fields. The values of the $loginid and $password variables are passed in from the form in authenticate.html using the post method.
Component 3 – Forgot Password
A registered user may forget his password to log into the website’s system. In this case, the user will need to supply his loginid for the system to retrieve his password and send the password to the user’s registered email address.
This is typically done through a simple HTML form. This HTML form typically contains 1 field and 2 buttons:
1. A login id field
2. A Submit button
3. A Reset button
1. A login id field
2. A Submit button
3. A Reset button
Assume that such a form is coded into a file named forgot.html. The following HTML code excerpt is a typical example. When the user has filled in all the fields, the forgot.php page is called when the user clicks on the Submit button.
[form name="forgot" method="post" action="forgot.php"]
[input name="login id" type="text" value="loginid" size="20"/][br]
[input type="submit" name="submit" value="submit"/]
[input type="reset" name="reset" value="reset"/]
[/form]
[input name="login id" type="text" value="loginid" size="20"/][br]
[input type="submit" name="submit" value="submit"/]
[input type="reset" name="reset" value="reset"/]
[/form]
The following code excerpt can be used as part of forgot.php to process the login request. It connects to the MySQL database and queries the table used to store the registration information.
@mysql_connect("localhost", "mysql_login", "mysql_pwd") or die("Cannot connect to DB!");
@mysql_select_db("tbl_login") or die("Cannot select DB!");
$sql="SELECT password, email FROM login_tbl WHERE loginid=’".$loginid.”’”;
$r = mysql_query($sql);
if(!$r) {
$err=mysql_error();
print $err;
exit();
}
if(mysql_affected_rows()==0){
print "no such login in the system. please try again.";
exit();
}
else {
$row=mysql_fetch_array($r);
$password=$row["password"];
$email=$row["email"];
@mysql_select_db("tbl_login") or die("Cannot select DB!");
$sql="SELECT password, email FROM login_tbl WHERE loginid=’".$loginid.”’”;
$r = mysql_query($sql);
if(!$r) {
$err=mysql_error();
print $err;
exit();
}
if(mysql_affected_rows()==0){
print "no such login in the system. please try again.";
exit();
}
else {
$row=mysql_fetch_array($r);
$password=$row["password"];
$email=$row["email"];
$subject="your password";
$header="from:you@yourdomain.com";
$content="your password is ".$password;
mail($email, $subject, $row, $header);
$header="from:you@yourdomain.com";
$content="your password is ".$password;
mail($email, $subject, $row, $header);
print "An email containing the password has been sent to you";
}
}
As in component 1, the code excerpt assumes that the MySQL table that is used to store the registration data is named tbl_login and contains 3 fields – the loginid, password and email fields. The value of the $loginid variable is passed from the form in forgot.html using the post method.
Conclusion
The previous example is to illustrate how a very basic login system can be implemented. The example can be enhanced to include password encryption and additional functionality – e.g. to allow users to edit their login information.
PHP MySQL Login Form
By jotorres, 9 Oct 2012
|
3.00 (2 votes)
|
|
Sign Up to vote vote 1vote 2vote 3vote 4vote 5
|
PHP MySQL Login Form
In this tutorial you will learn how to create a login form for your website using PHP and MySQL. This tutorial will be very basic, and very brief. It is to show the simplest way to have a user login to your website.
Login Form using PHP and MySQL:
Generally, it is mandatory to have a user login form in a website if you only want people with certain credentials view your content. It is a good way to keep your data secure from those who it is not intended to. Do you remember one of our previous tutorials on saving data to a database. Well we will use that same data and that same users table.
Since we already have our table created and stored data in it: See here: Save Records, we will query that same table for what the user has input on the login form.
Now let’s create the login form
login.php
Collapse | Copy Code
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Jotorres Login Form</title>
</head>
<body>
<form method="post" action="validate_login.php" >
<table border="1" >
<tr>
<td><label for="users_email">Email</label></td>
<td><input type="text"
name="users_email" id="users_email"></td>
</tr>
<tr>
<td><label for="users_pass">Password</label></td>
<td><input name="users_pass"
type="password" id="users_pass"></input></td>
</tr>
<tr>
<td><input type="submit" value="Submit"/>
<td><input type="reset" value="Reset"/>
</tr>
</table>
</form>
</body>
</html>
Now that we have the login form created, let’s go ahead and create the actual file for validation.
validate_login.php
Collapse | Copy Code
<?php
// Grab User submitted information
$email = $_POST["users_email"];
$pass = $_POST["users_pass"];
// Connect to the database
$con = mysql_connect("localhost","root","");
// Make sure we connected succesfully
if(! $con)
{
die('Connection Failed'.mysql_error());
}
// Select the database to use
mysql_select_db("my_dbname",$con);
$result = mysql_query("SELECT users_email, users_pass FROM users WHERE users_email = $email");
$row = mysql_fetch_array($result);
if($row["users_email"]==$email && $row["users_pass"]==$pass)
echo"You are a validated user.";
else
echo"Sorry, your credentials are not valid, Please try again.";
?>
If the username and password both are correct then output will be:
You are a validated user.
If any one of the field or both are incorrect then the output will be:
Sorry, your credentials are not valid. Please try again.
Exercise
In form of exercise, since we are little by little becoming PHP experts, you need to identify where would this script be vulnerable. Also, give reference to what can you do to prevent attacks.
Hints: SQL injection, mysql_real_escape_string, filter_var() with FILTER_SANITIZE_? I basically gave you more than what you need to answer those questions.
<?
session_start();
if(isset($_GET['reg'])){
$reg=$_GET['reg'];
}else{
$reg="";
}
if($reg==1){
$msg1="<font color="#FF0000"><b>Your details have been added,
please login</b></font>";
}elseif($reg==2){
$msg1="<font color="#FF0000"><b>You have been successfully
logged out.</b></font>";
}elseif($reg==3){
$msg1="<font color="#FF0000"><b>You have been redirected because you need to be logged on as administrator.</b></font>";
}
if(isset($_POST['submit'])){
if( empty($_POST['uname']) && (empty($_POST['upass']))){
header( "Location:Messages.php?msg=1" );
exit();
}
//transfer to shorter var
$n=$_POST['uname'];
$p=$_POST['upass'];
//connect to db
include('config.php');
$query="select * from user where uname='$n' and pw='$p'";
if($result=mysql_query($query)){
$row=mysql_fetch_assoc($result);
//check each var
if($n !=$row['uname']){
header( "Location:Messages.php?msg=2" );
exit();
}
if($p !=$row['pw']){
header( "Location:Messages.php?msg=11" );
exit();
}
if($row['isbanned']=='yes'){
header( "Location:Messages.php?msg=12" );
exit();
}
}//ifresult
//put in session vars
$_SESSION['level'] = $row['level'];
$_SESSION['status'] = 'logged';
$_SESSION['username'] = $n;
//This takes you to the admin pages; change this to take you to
wherever you want it //to go.
header("location:../admin/main.php");
exit;
}?>
session_start();
if(isset($_GET['reg'])){
$reg=$_GET['reg'];
}else{
$reg="";
}
if($reg==1){
$msg1="<font color="#FF0000"><b>Your details have been added,
please login</b></font>";
}elseif($reg==2){
$msg1="<font color="#FF0000"><b>You have been successfully
logged out.</b></font>";
}elseif($reg==3){
$msg1="<font color="#FF0000"><b>You have been redirected because you need to be logged on as administrator.</b></font>";
}
if(isset($_POST['submit'])){
if( empty($_POST['uname']) && (empty($_POST['upass']))){
header( "Location:Messages.php?msg=1" );
exit();
}
//transfer to shorter var
$n=$_POST['uname'];
$p=$_POST['upass'];
//connect to db
include('config.php');
$query="select * from user where uname='$n' and pw='$p'";
if($result=mysql_query($query)){
$row=mysql_fetch_assoc($result);
//check each var
if($n !=$row['uname']){
header( "Location:Messages.php?msg=2" );
exit();
}
if($p !=$row['pw']){
header( "Location:Messages.php?msg=11" );
exit();
}
if($row['isbanned']=='yes'){
header( "Location:Messages.php?msg=12" );
exit();
}
}//ifresult
//put in session vars
$_SESSION['level'] = $row['level'];
$_SESSION['status'] = 'logged';
$_SESSION['username'] = $n;
//This takes you to the admin pages; change this to take you to
wherever you want it //to go.
header("location:../admin/main.php");
exit;
}?>
No comments:
Post a Comment