Friday, 19 April 2013

Login form in PHP + MySQL

Create login.php and home.php

If valid username and password is entered by the user then he/she will access his/her HomePage.

login.php

where code and html document is there

<html>
<head>
<title>Login form</title>
<?php
if(isset($_POST['submit']))
{
$con=mysqli_connect(@"localhost","root","","demo");
// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }
$un=$_POST['username'];
$ps=$_POST['password'];

$result = mysqli_query($con,"SELECT * FROM tbladmin WHERE username='$un' and password='$ps'");
$row = mysqli_fetch_array($result);
$name = $row["username"];

$count=mysqli_num_rows($result);
  if($count==1)  {
 session_start();
 $_SESSION["user"]=$name;
 header("location:home.php");

  }
  else
  {
  echo "<div style=\"color:red\"><center>Invalid Username/Password</center></div>";
  }

mysqli_close($con);
}
?>
</head>

<body>
<form action="" method="post">
<center>
<h1>Admin LOGIN Form</h1>
<table >
<tr>
<td>
username:
</td>
<td>
 <input type="text" name="username">
</td>
</tr>
<tr>
<td>
password:
</td>
<td>
 <input type="password" name="password">
</td>
</tr>
<tr>
<td>
</td>
<td>
<input type="submit" name="submit" value="submit">
<input type="reset" name="reset" value="reset">
</td>
</tr>
</table>
</center>
</form>

</body>
</html>



home.php

Having the code to check session is started or Not.

<?php
session_start();
if(isset($_SESSION['user']))
{ $name=$_SESSION['user'];
 echo " welcome,$name";
}
else
{
 header("location:login.php");
}

?>

1 comment:

  1. Plz send the code with database file.(karthik99859808@gmail.com)

    ReplyDelete