, , , , , , , , , , ,

PHP Login Form or Login Script in PHP!!!

If you know how to create website in php and you started creating any php web site that allow user or admin to login then first thing comes in your mind is to create php login script or login form in php that allow user or admin to get login. For login the user must have their respective username and password which he enters in to login form page. To make his successful login we verified his username and password with MySQL database table which contain the username and password for all.

In this tutorial of php code for beginners we will show you step by step creation of your first php login form or php script for login. Basically we create one simple login form in html and connect this code with MySQL database and php script.

You can also use the JavaScript validation or jquery validation for your login php form.

Step 1:- Create a table “users” with the code below:




Image representing MySQL as depicted in CrunchBase

Image via CrunchBase

  username varchar(16),
  password char(16),
  UNIQUE (username)

Step 2:- Create a config.php file with the below:


$database = “mydata”;  // the name of the database.
$server = “localhost”;  // server to connect to.
$db_user = “root”;  // mysql username to access the database with.

The PHP logo displaying the Handel Gothic font.

The PHP logo displaying the Handel Gothic font. (Photo credit: Wikipedia)

$db_pass = “”;  // mysql password to access the database with.
$table = “users”;    // the table that this script will set up and use.
$link = mysql_connect($server, $db_user, $db_pass);
Step 3:- Create “register.html” file with following code:
<link rel=”stylesheet” type=”text/css” href=”style.css” />
<div id=”containt” align=”center”>
<form action=”login.php” method=”post”>
<div id=”header”><h2>Admin/Employee Login</h2></div>
            <td>Enter Username:</td>
            <td> <input type=”text” name=”username” size=”20″></td>
            <td>Enter Password:</td>
            <td><input type=”password” name=”password” size=”20″></td>
             <td><input type=”submit” value=”Log In”></td>
             <td><a href=”signup.html”>Sign Up</a></td>
Step 4:- Last step is Create “login.php” file with following code:
include(“config.php”); //including config.php in our file
$username = $_POST[“username”]; //Storing username in $username variable.
$password = $_POST[“password”]; //Storing password in $password variable.
$match = “select id from $table where username = ‘”.$_POST[‘username’].”‘
and password = ‘”.$_POST[‘password’].”‘;”;
$qry = mysql_query($match);
$num_rows = mysql_num_rows($qry);
 if ($num_rows <= 0) {
echo “Sorry, there is no username $username with the specified password.”;
echo “Try again”;
} else {
$_SESSION[‘user’]= $_POST[“username”];
// It is the page where you want to redirect user after login.
Now your PHP login form is ready to use.