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


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.

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

	echo "Login successfull.. You will be redirected to your personal page.."; 
	header( "refresh
		2;url=../Form/viewdtls.php" ); 

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