- PHP Basics
- Learn PHP
- PHP Comments
- PHP Data Types
- PHP Variables
- PHP Operators
- PHP echo
- PHP print
- PHP echo vs. print
- PHP if else
- PHP switch
- PHP for Loop
- PHP while Loop
- PHP do...while Loop
- PHP foreach Loop
- PHP break and continue
- PHP Arrays
- PHP print_r()
- PHP unset()
- PHP Strings
- PHP Functions
- PHP File Handling
- PHP File Handling
- PHP Open File
- PHP Create a File
- PHP Write to File
- PHP Read File
- PHP feof()
- PHP fgetc()
- PHP fgets()
- PHP Close File
- PHP Delete File
- PHP Append to File
- PHP Copy File
- PHP file_get_contents()
- PHP file_put_contents()
- PHP file_exists()
- PHP filesize()
- PHP Rename File
- PHP fseek()
- PHP ftell()
- PHP rewind()
- PHP disk_free_space()
- PHP disk_total_space()
- PHP Create Directory
- PHP Remove Directory
- PHP Get Files/Directories
- PHP Get filename
- PHP Get Path
- PHP filemtime()
- PHP file()
- PHP include()
- PHP require()
- PHP include() vs. require()
- PHP and MySQLi
- PHP and MySQLi
- PHP MySQLi Setup
- PHP MySQLi Create DB
- PHP MySQLi Create Table
- PHP MySQLi Connect to DB
- PHP MySQLi Insert Record
- PHP MySQLi Update Record
- PHP MySQLi Fetch Record
- PHP MySQLi Delete Record
- PHP MySQLi SignUp Page
- PHP MySQLi LogIn Page
- PHP MySQLi Store User Data
- PHP MySQLi Close Connection
- PHP Misc Topics
- PHP Object Oriented
- PHP new Keyword
- PHP Cookies
- PHP Sessions
- PHP Date and Time
- PHP GET vs. POST
- PHP File Upload
- PHP Image Processing
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:
Now enter the data say fresherearth as Username and fresherearth@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 = "fresherearth"; $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", "", "fresherearth"); 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", "", "fresherearth"); 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 fresherearth.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 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", "", "fresherearth"); 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:
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:
Now let me provide the registered username and password, that is fresherearth as username and fresherearth@123 as password:
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.
« Previous Tutorial Next Tutorial »