PHP MySQLi Login Page or Form

This article is created to describe, how to create a login page or form using PHP MySQLi object-oriented and procedural script.

In this article, first I will create a simple and basic login system, that consists of following three files:

  • A index.php file, consists of HTML login form
  • A login.php file, consists of PHP MySQLi script to handle form data, to login
  • A welcome.php file, to execute after verifying the user

And at last of this article, I will create a complete login page that consists of login form and the data handler script at the same place. Also, I will style the login form, to make it looks impressive. But for now, let's start with simple and basic one.

PHP MySQLi Login Page - HTML Form to Get Login Data

<H2>Login</H2>

<FORM action="login.php" method="post">
   Username: <INPUT type="text" name="username" required><BR>
   Password: <INPUT type="text" name="password" required><BR>
   <BUTTON type="submit">Login</BUTTON><HR>
</FORM>

<P>Have not registered ? <a href="register.php">Register</a></P>

The output is:

php mysql login form

Now enter the data say codescracker as Username and codescracker@1234 as Password. But before clicking on the Login button, let me first create the login.php file using both, object-oriented as well as procedural style. Then will create the welcome.php file.

PHP MySQLi Object-Oriented Script to Handle Login Data

<?php
   if($_SERVER["REQUEST_METHOD"] == "POST")
   {
      $server = "localhost";
      $user = "root";
      $pass = "";
      $db = "codescracker";
      
      $conn = new mysqli($server, $user, $pass, $db);
      
      if($conn -> connect_errno)
      {
         echo "Database connection failed!<BR>";
         echo "Reason: ", $conn -> connect_error;
         exit();
      }
      else
      {
         $uname = $_POST["username"];
         $pass = $_POST["password"];
         
         $sql = "SELECT * FROM users WHERE Username='$uname' and Password='$pass'";
         $stmt = $conn -> query($sql);
         
         if($stmt)
         {
            $_SESSION['log'] = $uname;
            header('Location: welcome.php');
            exit();
         }
         else
         {
            echo "Something went wrong!<BR>";
            echo "Error Description: ", $conn -> error;
      }
   }
   $conn -> close();
?>

Note - The mysqli() is used to open a connection to the MySQL database server, in object-oriented style.

Note - The new keyword is used to create a new object.

Note - The connect_errno is used to get/return the error code (if any) from last connect call, in object-oriented style.

Note - The connect_error is used to get the error description (if any) from last connection, in object-oriented style.

Note - The exit() is used to terminate the execution of the current PHP script.

Note - The query() is used to perform query on the MySQL database, in object-oriented style.

Note - The header() function is used to send raw HTTP header. Most of the time, used for redirection.

Note - The error is used to return the description of error (if any), by the most recent function call, in object-oriented style.

Note - The close() is used to close an opened connection, in object-oriented style.

The above script or code, can also be written in this way:

<?php
   if($_SERVER["REQUEST_METHOD"] == "POST")
   {
      $conn = new mysqli("localhost", "root", "", "codescracker");
      if(!$conn->connect_errno)
      {
         $uname = $_POST["username"];
         $pass = $_POST["password"];
         $sql = "SELECT * FROM users WHERE Username='$uname' and Password='$pass'";
         if($conn->query($sql))
         {
            $_SESSION['log'] = $uname;
            header('Location: welcome.php');
            exit();
         }
      }
      $conn->close();
   }
?>

PHP MySQLi Procedural Script to Handle Login Data

Here is the script of login.php file, in PHP MySQLi procedural style:

<?php
   if($_SERVER["REQUEST_METHOD"] == "POST")
   {
      $conn = mysqli_connect("localhost", "root", "", "codescracker");
      if(!mysqli_connect_errno())
      {
         $uname = $_POST["username"];
         $pass = $_POST["password"];
         $sql = "SELECT * FROM users WHERE Username='$uname' and Password='$pass'";
         if(mysqli_query($conn, $sql))
         {
            $_SESSION['log'] = $uname;
            header('Location: welcome.php');
            exit();
         }
      }
      mysqli_close($conn);
   }
?>

Note - The mysqli_connect() is used to open a connection to the MySQL database server, in procedural style.

Note - The mysqli_connect_errno() is used to get/return the error code (if any) from last connect call, in procedural style.

Note - The mysqli_query() is used to perform query on the MySQL database, in procedural style.

Note - The mysqli_close() is used to close an opened connection to the MySQL database, in procedural style.

PHP MySQLi Script for welcome.php File

Here is the script of welcome.php file:

<?php 
   session_start();
   
   if(isset($_SESSION['log']))
   {
      echo "Welcome to codescracker.com!<BR>";
      echo "You are an authorized person.";
      
      // block of code, to process further...
   }
   else
   {
      header('Location: index.php');
      exit();
   }
   
   // block of code, to process further...
?>

Now click on the Login button. After clicking on the Login button, the form data will be submitted or sent to the login.php file. And after verifying the user, the login.php page sends the user to welcome.php page. Here is the final output, we will see, after successful login:

php mysql login page

PHP MySQLi Complete Login Page

I am going to use prepared statements to create a complete login system, using PHP MySQLi object-oriented script, to make the login system, more safe and secure.

<?php
   error_reporting(0);
   if($_SERVER["REQUEST_METHOD"] == "POST")
   {
      function validData($x)
      {
         $x = trim($x);
         $x = stripslashes($x);
         $x = htmlspecialchars($x);
         return $x;
      }
      $conn = new mysqli("localhost", "root", "", "codescracker");
      if(!$conn->connect_errno)
      {
         $uname = validData($_POST["username"]);
         $pass = validData($_POST["password"]);
         if(!empty($uname) and !empty($pass))
         {
            $sql = "SELECT * FROM users WHERE Username=? and Password=?";
            $stmt = $conn->prepare($sql);
            $stmt->bind_param("ss", $uname, $pass);
            if($stmt->execute())
            {
               $result = $stmt->get_result();
               if($result->num_rows)
               {
                  $_SESSION['log'] = $uname;
                  header('Location: welcome.php');
                  exit();
               }
               else
                  $err = "Wrong Username and/or Password";
            }
         }
      }
      $conn->close();
   }
?>
<HTML>
<HEAD>
<STYLE>
   .form{width: 280px; margin: auto; padding: 12px; border-left: 2px solid #ccc;
      border-radius: 18px;}
   h2{color: purple; text-align: center;}
   input{padding: 12px; width: 100%; margin-bottom: 12px; border: 0px;
      border-radius: 6px; background-color: #ccc;}
   button{margin: 14px 0px; width: 100%; background-color: #008080; color: white;
      padding: 12px; font-size: 1rem; border-radius: 6px;}
   p{text-align: center;}
   button:hover{cursor: pointer;}
   .red{text-align: center; color: red;}
</STYLE>
</HEAD>
<BODY>

<DIV class="form">
   <H2>Login</H2>
   <FORM name="login" method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
      <LABEL>Username
      <?php
         if(!empty($err))
            echo "<SPAN class=\"red\">*</SPAN>";
         else
            echo "*";
      ?></LABEL><BR>
      <INPUT type="text" name="username" placeholder="Enter Username" required><BR>
      <LABEL>Password
      <?php
         if(!empty($err))
            echo "<SPAN class=\"red\">*</SPAN>";
         else
            echo "*";
      ?></LABEL><BR>
      <INPUT type="text" name="password" placeholder="Enter Password" required><BR>
      <BUTTON type="submit">Login</BUTTON>
   </FORM>
   <?php
      echo "<DIV class=\"red\">"; 
      if(isset($err))
         echo $err;
      echo "</DIV>";
   ?>
   <P>Have not registered ? <a href="login.php">Register</a></P>
</DIV>

</BODY>
</HTML>

Here is the initial output produced by above PHP example:

php mysqli login page

Now let me enter some wrong input first, say unknown as username and unknown as password. Here is the output, after hitting on the Login button:

php mysqli login form

Now let me provide the registered username and password, that is codescracker as username and codescracker@123 as password:

php mysqli login system

The output you are seeing, is the welcome.php file. You can modify this file, based on your requirement.

Note - The error_reporting() is used to define, what errors to be displayed.

Note - The prepare() is used to prepare an SQL statement before its execution on the MySQL database, in object-oriented style, to avoid SQL injection.

Note - The bind_param() is used to bind variables to a prepared statement, as parameters, in object-oriented style.

Note - The execute() is used to execute a prepared statement on the MySQL database, in object-oriented style.

PHP Online Test


« Previous Tutorial Next Tutorial »