- PHP Basics
- PHP Home
- PHP Environment Setup
- PHP Getting Started
- PHP Basic Syntax
- PHP echo
- PHP print
- PHP echo Vs print
- PHP Comments
- PHP Data Types
- PHP Variables
- PHP Variable Scope
- PHP gettype()
- PHP Constants
- PHP Operators
- PHP Program Control
- PHP Decision Making
- PHP if-elseif-else
- PHP switch
- PHP Loops
- PHP for Loop
- PHP while Loop
- PHP do-while Loop
- PHP foreach Loop
- PHP break & continue
- PHP Popular Topics
- PHP Arrays
- PHP print_r()
- PHP Strings
- PHP Functions
- PHP References
- PHP Object Oriented
- PHP Object Oriented
- PHP Classes & Objects
- PHP Member Variable
- PHP Member Function
- PHP Encapsulation
- PHP Data Abstraction
- PHP Inheritance
- PHP Constructor Destructor
- PHP Polymorphism
- PHP Web Developments
- PHP Web Developments
- PHP GET & POST
- PHP Read Requested Data
- PHP File Handling (I/O)
- PHP File Handling (I/O)
- PHP fopen() | Open File
- PHP Create a File
- PHP fwrite() | Write to File
- PHP fread() | Read File
- PHP feof()
- PHP fgetc()
- PHP fgets()
- PHP fclose() | Close File
- PHP unlink() | Delete File
- PHP Append to File
- PHP copy() | Copy File
- PHP file_get_contents()
- PHP file_put_contents()
- PHP file_exists()
- PHP filesize()
- PHP rename() | Rename File
- PHP fseek()
- PHP ftell()
- PHP rewind()
- PHP disk_free_space()
- PHP disk_total_space()
- PHP mkdir() | Create Directory
- PHP rmdir() | Remove Directory
- PHP glob() | Get Files/Directories
- PHP basename() | Get filename
- PHP dirname() | Get Path
- PHP filemtime()
- PHP file()
- PHP Advanced
- PHP Cookies
- PHP Sessions
- PHP Send Emails
- PHP Serialization
- PHP Namespaces
- PHP File Upload
- PHP Date and Time
- PHP Image Processing
- PHP Regular Expression
- PHP Predefined Variables
- PHP Error Handling
- PHP Debugging
- PHP and MySQLi Tutorial
- PHP and MySQLi Home
- PHP MySQLi Setup
- PHP MySQLi Create DB
- PHP MySQLi Create Table
- PHP MySQLi Connect to DB
- PHP MySQLi Insert Record
- PHP MySQLi Fetch Record
- PHP MySQLi Update Record
- PHP MySQLi Delete Record
- PHP MySQLi SignUp Page
- PHP MySQLi LogIn Page
- PHP MySQLi Store User Data
- PHP MySQLi Close Connection
- PHP connect_errno
- PHP connect_error
- PHP query()
- PHP fetch_row()
- PHP fetch_assoc()
- PHP fetch_array()
- PHP free_result()
- PHP error
- PHP prepare()
- PHP bind_param()
- PHP execute()
- PHP fetch()
- PHP store_result()
- PHP num_rows
- PHP bind_result()
- PHP get_result()
- PHP mysqli_result Class
- PHP Error Constants
- PHP mysqli_driver()
- PHP Misc
- PHP error_reporting()
- PHP Escape Special Characters
- PHP htmlspecialchars()
- PHP new
- PHP header()
- PHP getallheaders()
- PHP empty()
- PHP isset()
- PHP unset()
- PHP exit()
- PHP exit Vs break
- PHP include()
- PHP require()
- PHP include() Vs require()
- PHP AJAX & XML
- PHP AJAX
- PHP XML
- PHP File Handling Functions
- PHP abs()
- PHP Test
- PHP Online Test
- Give Online Test
- All Test List
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 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 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:
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 codescracker as username and codescracker@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 »