Creating a Login Form Using PHP and Mysql

Hello Guys Welcome to Coding Gurus Online Portal ...!

PHP Login Script

After creating user login Page , we need to write PHP script. This script will authenticate user and will redirect them to their private page on successful login.

User Authentication

In this step we will ,
1. Get user login details sent via Login form using methods GET/POST.
2. Compare user input with database to authenticate.
3. Add valid authenticated user data into session.

Once users logged in successfully, then they will be redirected to the user dashboard or profile page or anything.In this example, we have an dashboard page showing Welcome message with logout link. The code for PHP login is,

Creating a file connection.php

<?php
$host="localhost"; // Host name
$username="coding"; // Mysql username
$password="coding"; // Mysql password
$db_name="codinggurus"; // Database name
$tbl_name="coding"; // Table name

// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");

// username and password sent from form
$myusername=$_POST['myusername'];
$mypassword=$_POST['mypassword'];

// To protect MySQL injection
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$myusername = mysql_real_escape_string($myusername);
$mypassword = mysql_real_escape_string($mypassword);

$sql="SELECT * FROM $tbl_name WHERE username='$myusername' and password='$mypassword'";
$result=mysql_query($sql);

// Mysql_num_row is counting table row
$count=mysql_num_rows($result);

// If result matched $myusername and $mypassword, table row must be 1 row
if($count==1){

// Register $myusername, $mypassword and redirect to file "dashboard.php"
session_register("myusername");
session_register("mypassword");
header("location:dashboard.php");
}
else {
echo "Wrong Username or Password";
}
?>

Once the user gets authenticated , if the login details are correct then he will be redirected to dashboard page.


Creating a file dashboard.php


<?php
session_start();
if(!session_is_registered(myusername)){
header("location:login.php");
}
?>

<html>
<body>
Login Successful
<a href="logout.php">Log out </body>

</html>

Creating a file logout.php


<?php
session_start();
session_destroy();
?>


Back