How to create PHP Mysql Login Script using session

Last updated on December 27th, 2022 at 10:05 am

This login script can check whether user exist in the MySQL database, Create session and redirect user to the secure page. If session is not set it will automatically redirect to login page. I have also added a logout page where users can logout and the system will automatically clear user sessions.

First step in the process is to create a database named userlogin. In that we have 3 columns named ID, username and password. I am also inserting a test data to the database so that we can check whether the script is working as expected.

Our 1st step is to Create table “mydata” inside database “userlogin”.

CREATE DATABASE userlogin;
USE userlogin;
CREATE TABLE mydata (
id INT(4) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(30) NOT NULL,
password VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP
)

Inserting data for table `mydata`

INSERT INTO mydata (username, password) VALUES ('user1', 'pass123');
INSERT INTO mydata (username, password) VALUES ('user2', 'pass345');

Next step is to create an index.php file with the login fields.

Create file main_login.html.

<?php
if(isset($_GET["msg"]))
{
echo $_GET["msg"];
}
?><table width="300" border="0" align="center" cellpadding="0" cellspacing="1" bgcolor="#CCCCCC">
<tr>
<form name="form1" method="post" action="checklogin.php">
<td>
<table width="100%" border="0" cellpadding="3" cellspacing="1" bgcolor="#FFFFFF">
<tr>
<td colspan="3"><strong>Member Login </strong></td>
</tr>
<tr>
<td width="78">Username</td>
<td width="6">:</td>
<td width="294"><input name="myusername" type="text" id="myusername"/></td>
</tr>
<tr>
<td>Password</td>
<td>:</td>
<td><input name="mypassword" type="password" id="mypassword"/></td>
</tr>
<tr>
<td> </td>
<td> </td>
<td><input type="submit" name="Submit" value="Login"/></td>
</tr>
</table>
</td>
</form>
</tr>
</table>

Create a file named checklogin.php and add the following codes

Now we have the database and login page ready.
Next step in the process is to create a PHP files which has the ablity to check the username and password submitted from the HTML file. Create sessiong and redirect user to login page. Also remove session variables once the user is logged out. Each line of code below is properly commented for your convenience.

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

// Connect to server and select databse.
$con = mysqli_connect("$host", "$username", "$password")or die("cannot connect");
$obj = mysqli_select_db($con,"$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=mysqli_query($con,$sql);

// Mysql_num_row is counting table row
$count=mysqli_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 "login_success.php"
session_start();
$_SESSION["user"] = $myusername;
header("location:login_success.php");
}
else {
echo "Wrong Username or Password";
header("location:index.php?msg=Wrong Username/Password");
}
?>

Create file login_success.php.

<?php
session_start();
echo 'Welcome '.$_SESSION["user"];
//If session is not set
if(!isset($_SESSION['user']))
{
header("location:index.php");
}
?>

<html>
<body>
You Have Successfully Logged In.<br />

<a href="logout.php">Log Out </a></body>
</html>
Create file logout.php
<?php
session_start();
//Remove all sessions and redirect to login page
session_destroy();
header("location:index.php");
?>

Note: I have updated this tutorial with mysqli_connect instead of mysql_connect which was posted by us back in 2009. Some of the parameters like session_register has been depreciated in newer versions of PHP. Hence I thought of updating this tutorial with more details with the depreciated part removed. The code above has been tested and everything is working as expected. I have also included a Demo for your convenience. Happy coding 🙂 .

That is all you are done. Check this Demo on how this script works.

You might also be interested in creating a complete user registration system using PHP MySQL

If you are using PHP 5 or lower versions you can take a look at this tutorial to create tag cloud using mysql on how to use mysql_connect instead of mysqli_connect.

11 Comments

  1. xhaaejdqjy

    a good one..

  2. gfsfcvknwln

    Good a very simple script for loging in using php….nice

  3. tvnpmsm

    very simple login script i have ever seen..

  4. fuowhrywnwh

    gud one

  5. Esod

    Work very fine and it’s was so easy to use !

    Thank’s a lot !!!

  6. umair

    this login script is very helpful for new visitor must see this code

  7. n

    gud one!
    TQ

  8. saravana

    it’s really awesome. i have never seen before…

    Thanks for easy script

  9. whaa...

    whaaaaaaaaaaa………….

  10. Areen

    your a Genius….. Thnks to made us life easier…..

  11. Full Container Load

    First and easy script.