Authentication of username and password using PHP(MySQL)

20 Jan 2013

For sites that need login facilities, entered username and password should be checked with the database to verify the username. Here is an example for doing this. Form.html has a form to enter login and password details. When clicking the submit button it will pass the login username and password to auth.php.Codes needed for both files are given below.

Form.html

<form action='https://auth.php' method='post' name='form1' class='loginbg' id='form1'>  
<p align='left'>UserName  
<input name='username' type='text'size='10'/>  
</p>  
<p align='left'>Password  
<input name='password' type='password' size='10'/>  
</p>  
<p align="center">  
<input name='Login' type="submit" class="login" id="Login" value="login"/>
</p>
</form>

auth.php

stripslashes($username); is used to remove any slashes present in the field. This is used to prevent SQL injection. Here student details is the database and details is the table name under the database.

<?php  
error_reporting(0);  
session_start();  
$_SESSION['authuser']=0;  
$username=$_POST['username'];  
$password=$_POST['password'];  
$username = stripslashes($username);  
$password = stripslashes($password);  
$con = mysql_connect("localhost","root","");   
if (!$con) 
{ 
	die('Sorry ... Could not connect
		' . mysql_error().'Plz try again later'); 
} 

mysql_select_db("student details", $con); 

$vrfy=mysql_query("SELECT `Id` FROM `details` WHERE `User_Name`='$username' AND Password='$password'"); 
$rslt = mysql_fetch_array($vrfy); 
if($rslt['Id']!='') 
{ 

	$_SESSION['username']=$username; 
	$_SESSION['password']=$password; 
	if($rslt['Id']==0) 
		$_SESSION['authuser']=2; 
	else 
		$_SESSION['authuser']=1; 
	echo "Login successfull.. You will be redirected to your personal page.."; 
	header( "refresh
		2;url=../Form/viewdtls.php" ); 
} 

else 
{ 
	echo "Login Failed .. Please check your password and user id.\n You will be redirected to home page."; 
	header( "refresh
		2;url=../index.php" ); 
} 
?>