It seems like you are using an ad blocker. To enhance your experience and support our website, please consider:

  1. Signing in to disable ads on our site. Our users don't see ads
  2. Or, Sign up if you don't have an account yet
  3. Or, disable your adblocker by doing this:
    • Click on the adblocker icon in your browser's toolbar.
    • Select "Pause on this site" or a similar option for lancecourse.com.

Simple Login script with PHP

By zooboole

Hey guys, in this tutorial I will show how to create a login script using PHP and MYSQL. The local server used in this tutorial is XAMPP. If you don't have XAMPP you can download here.

What you have to do after installing XAMPP?

  • Go to Start and open XAMPP control panel
  • Start Apache and MySQL. It should look like below figure

Xampp

  • Now you can close the XAMPP control panel.

Create our database and tables

  • Open your browser and type http://localhost in the address bar.
  • Click on phpMyAdmin on the left side as shown below.

PhpMyAdmin

  • On the left side of the new page you will see the list of available databases
  • Choose one of these databases and create a table inside by clicking on `New' like in the image bellow

Database and tables

In the above figure I created new table inside the databaselearn and the table name is echocodea. Any name can be given has a table name.

The structure of the table echocodea:

CREATE TABLE `echocodea`(
id  int(11) NOT NULL    auto_increment,
username    varchar(50) NOT NULL    default,
email   varchar(50) NOT NULL    default,
password    varchar(50) NOT NULL    default,
PRIMARY KEY (`id`)
) 

What you have to do after creating database?

  • Create a new folder to keep your project in; for example SignIn
  • Open your favorite text editor(notepad, sublime text, etc) and create a new file. Name it index.php and save it in your folder SignIn.
  • Copy and paste the below code in index.php

    <div id="login">
        <div id="sub_login">
            <h5 id="log_head">LogIn</h5><hr>
            <span><?= $error;?></span>
            <form action="checklogin.php" method="post">        
                <input type="text" name="username" placeholder="USERNAME">
                <span><?= $fields_error;?></span><br>
                <input type="password" name="password" placeholder="PASSWORD">
                <span><?= $fields_error1;?></span><br><br>
                <input id="log_submit" type="submit" name="submit" Value="LogIn">
            </form>

        </div>
    </div>
  • After creating index.php create a new file and name it checklogin.php.
  • Copy and paste the below code inside checklogin.php.

    <?PHP
        session_start();
        $fields_error = ""; 
        $fields_error1 = ""; 
        $error =""; 
        if(isset($_POST['submit']))
        {
            if(empty($_POST['username']) || trim($_POST['username']) =='' )
            {
                $fields_error= "Username is required";
            }else {
                $username=htmlspecialchars($_POST['username'], ENT_QUOTES, 'UTF-8');
            }

            if(empty($_POST['password'])  || trim($_POST['password']) =='' ) 
            {
                $fields_error1 = "Password is required";
            }else {
                $password = password_hash($_POST['password'], PASSWORD_DEFAULT);
            }

            if(empty($fields_error) && empty($fields_error1))
            {
                $connection = mysql_connect("localhost","root","");
                $db = mysql_select_db("learn", $connection) or die("cannot select DB");     
                $result = mysql_query("SELECT * FROM echocodea WHERE username='$username');
                $data = mysql_num_rows($result);
                if($data){
                  if(password_verify($password, $data['password'])){
                      $_SESSION["username"] = $username;
                      echo htmlspecialchars(strip_tags($_POST['username']), ENT_QUOTES, 'UTF-8');   
                  }else{
                     $error = "OOOPS..Username or Password is wrong!!!";
                  }

                }else {
                    $error = "OOOPS..Username or Password is wrong!!!";
                }

            mysql_close ($connection);
            }

        }

    ?>

In the above code, this portion allows us to initialize error variables with null value

$fields_error = ""; 
$fields_error1 = "";
$error =""; 

.

if(isset($_POST['submit']))

This indicates if login button is pressed in index.php.

if(empty($_POST['username']) || trim($_POST['username']) =='' ) 

and

if(empty($_POST['password'])  || trim($_POST['password']) =='' ) {

checks whether the username and password field are empty or not. If any of the field is empty then it displays the error message if not empty then the username and password are respectively stored in $username and $password.

if(empty($fields_error) && empty($fields_error1))

Checks whether the error variables declared at the beginning are empty or not. If there are empty, it means every was fine then the below code will be executed.

$connection = mysql_connect("localhost","root","");

This is connection to the database server.

$db = mysql_select_db("learn", $connection) or die("cannot select DB");

This line will now check in our table if there is a user who has this uername and password store before.

$result = mysql_query("SELECT * FROM echocodea WHERE username='$username' ");

This line selects the results of the above query and stores in $data.

$data = mysql_num_rows($result);

This following 3 lines check if there is record that corresponds to our username and password. If there is, then that username is $username and we display ( echo htmlspecialchars(strip_tags($_POST['username']), ENT_QUOTES, 'UTF-8'); ) the given user name to show the user that his username and password match with our records.

if($data){
    $_SESSION["username"] = $username;
    echo $_SESSION[“username”];  

If there is no such username or password then it prints username or password is wrong.

Finally mysql_close ($connection); closes the connection to the database.

  • Again let's create a new file for styling the form with the name style.css and write the below code inside it.

    #login {
        width: 30%;
        margin-left:10%;
        margin-top:0.5%;
        font-family: 'Raleway', sans-serif; 
    }
    #sub_login {
        width: 95%;
        padding: 2% 8% 7%;
        border: 2px solid gray;
        border-radius: 10px;
        font-family: raleway;
        margin-left:0%;
        margin-top:1%;
    }
    span {
        color:red;  
    }

    #log_head {
        padding: 6% 8%;
        margin: 2% 4%;
        text-align:center;
        border-radius: 10px 10px 0 0;
        font-size:200%;
    }

    #log_submit{
        padding: 10px;
        font-size: 18px;
        background: linear-gradient(#069 5%, #068 100%);
        border: 1px solid #ccc;
        color: #fff;
        font-weight: bold;
        cursor: pointer;
        width: 96%;
        border-radius: 5px;
        margin-bottom:10px;
    }

    #log_submit:hover {
        background: linear-gradient(#069 5%, #068 100%);
    }

    input[type=text],input[type=password],textarea{
        width: 95.7%;
        height: 30px;
        padding: 5px;
        margin-bottom: 5px;
        margin-top: 5px;
        border: 2px solid #ccc;
        color: #4f4f4f;
        font-size: 16px;
        box-shadow:inset 0 1px 2px rgba(0,0,0,0.18);
    }

    .forgot{
        text-decoration: none;
        display: block;
        float: left;
        margin-top: 5px;
        margin-left: 5px;
        color:blue;
    }

And we're done!

I used mysql_* extension which is deprecated today and can be a serious security issue (refering tosql injections). So, in a serious project I prefer you use mysqli_* or pdo. Check out here an example of how pdo can be used: Create a simple news site with PHP and MySQL using PDO

Thanks for following, if you like share.

Last updated 2024-01-11 UTC