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

$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

// 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'";

// Mysql_num_row is counting table row

// If result matched $myusername and $mypassword, table row must be 1 row

// Register $myusername, $mypassword and redirect to file "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


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


Creating a file logout.php