PHP mysqli code to create a 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 scripts.

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

And at the end of this article, I will create a complete login page that consists of a login form and the data handler script at the same place. Also, I will style the login form to make it look impressive. But for now, let's start with a 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 the Username and codescracker@1234 as the Password. But before clicking on the Login button, let me first create the login.php file using both object-oriented and procedural styles. Then I 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() function 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 or return the error code (if any) from the last connect call in object-oriented style.

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

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

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

Note: The header() function function is used to send raw HTTP headers. The majority of the time, it is used for redirection.

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

Note: The close() function 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 the 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() function is used to open a connection to the MySQL database server in procedural style.

Note: The mysqli_connect_errno() function is used to get or return the error code (if any) from the last connect call in procedural style.

Note: The mysqli_query() function is used to perform queries on the MySQL database in procedural style.

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

PHP mysqli script for the welcome.php file

Here is the script for the 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 the welcome.php page. Here is the final output, which 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 the 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 the Login button:

php mysqli login form

Now let me provide the registered username and password, which are 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 requirements.

Note: The error_reporting() function is used to define what errors should be displayed.

Note: The prepare() function 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() function is used to bind variables to a prepared statement as parameters in object-oriented style.

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

PHP Online Test


« Previous Tutorial Next Tutorial »


Liked this post? Share it!