- 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 exit()
- PHP exit() vs. break
- PHP isset()
- 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 mysqli Tutorial
- PHP mysqli Tutorial
- PHP and MySQL Setup
- PHP mysqli: Create Database
- PHP mysqli: Create Table
- 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 Functions
- PHP mysqli_connect()
- PHP mysqli_close()
- PHP mysqli_connect_errno()
- PHP mysqli_connect_error()
- PHP mysqli_query()
- PHP mysqli_fetch_row()
- PHP mysqli_fetch_assoc()
- PHP mysqli_fetch_array()
- PHP mysqli_free_result()
- PHP mysqli_error()
- PHP mysqli_prepare()
- PHP mysqli_stmt_bind_param()
- PHP mysqli_stmt_execute()
- PHP mysqli_stmt_fetch()
- PHP mysqli_stmt_store_result()
- PHP mysqli_stmt_num_rows()
- PHP mysqli_stmt_bind_result()
- PHP mysqli_stmt_get_result()
- PHP mysqli_result class
- PHP mysqli_report()
- PHP error_reporting()
- PHP mysqli_real_escape_string()
- PHP htmlspecialchars()
- PHP Misc Topics
- PHP Object Oriented
- PHP new Keyword
- PHP header()
- PHP getallheaders()
- PHP Cookies
- PHP Sessions
- PHP Date and Time
- PHP GET vs. POST
- PHP File Upload
- PHP Image Processing
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:
- A "index.php" file consists of an HTML login form.
- A "login.php" file is made up of PHP mysqli script to handle form data and login.
- A "welcome.php" file, to execute after verifying the user.
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:
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 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:
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:
Now let me provide the registered username and password, which are 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 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.
« Previous Tutorial Next Tutorial »