Skip to content
September 6, 2026
  • Turning Your Website into a Fully Functional and Secure Android and iOS Application
  • Securing Your CodeIgniter Application Against SQL Attacks
  • Creating a Web Application Installer with PHP PDO, MySQL, JavaScript, and Bootstrap
  • Create a fun card game in Python

Dan O'Riordan

Web Application Developer

  • Home
  • PHP
  • Codeigniter
  • HTML
  • Javascript
  • Visual Basic
  • C#
  • C++
  • CSS
  • Python
Codes
  • Turn website into mobile application

    Turning Your Website into a Fully Functional and Secure Android and iOS Application

    2 years ago
  • Securing Your CodeIgniter Application Against SQL Attacks

    2 years ago
  • Application Installer

    Creating a Web Application Installer with PHP PDO, MySQL, JavaScript, and Bootstrap

    2 years ago
  • Create a fun card game in Python

    2 years ago2 years ago
  • Wordpress

    Criteria for Creating a WordPress Plugin Using PHP 8

    2 years ago
  • 10 Unique Web Application Ideas & How to Build Them Without Losing Your Sanity

    2 years ago2 years ago
  • Home
  • PHP
  • Secure Login using MySQLi
  • PHP

Secure Login using MySQLi

Danno2 years ago2 years ago14 mins

In this post, we will implement a secure login system using PHP’s mysqli extension with prepared statements. This approach helps prevent SQL injection attacks and enhances the overall security of user authentication. Additionally, we will create session variables to maintain user state after successful login. Error handling and exception handling will be incorporated to ensure robustness.

<?php
session_start(); // Start the session

// Database connection parameters
$host = 'localhost';
$username = 'your_username';
$password = 'your_password';
$database = 'your_database';

try {
    // Create a new mysqli connection
    $mysqli = new mysqli($host, $username, $password, $database);

    // Check for connection errors
    if ($mysqli->connect_error) {
        throw new Exception('Connection failed: ' . $mysqli->connect_error);
    }

    // Check if the form is submitted
    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        // Retrieve and sanitize user input
        $email = filter_var(trim($_POST['email']), FILTER_SANITIZE_EMAIL);
        $password = trim($_POST['password']);

        // Prepare the SQL statement
        $stmt = $mysqli->prepare("SELECT id, password FROM users WHERE email = ?");
        if (!$stmt) {
            throw new Exception('Prepare failed: ' . $mysqli->error);
        }

        // Bind parameters
        $stmt->bind_param("s", $email);

        // Execute the statement
        if (!$stmt->execute()) {
            throw new Exception('Execute failed: ' . $stmt->error);
        }

        // Store the result
        $stmt->store_result();

        // Check if the user exists
        if ($stmt->num_rows === 1) {
            // Bind the result variables
            $stmt->bind_result($userId, $hashedPassword);
            $stmt->fetch();

            // Verify the password
            if (password_verify($password, $hashedPassword)) {
                // Password is correct, create session variables
                $_SESSION['user_id'] = $userId;
                $_SESSION['email'] = $email;

                // Redirect to a secure page
                header("Location: dashboard.php");
                exit();
            } else {
                echo "Invalid password.";
            }
        } else {
            echo "No user found with that email address.";
        }

        // Close the statement
        $stmt->close();
    }
} catch (Exception $e) {
    // Handle exceptions
    echo 'Error: ' . $e->getMessage();
} finally {
    // Close the database connection
    $mysqli->close();
}
?>
  1. Session Management: We start the session to manage user state.
  2. Database Connection: A connection to the MySQL database is established using mysqli. Error handling is implemented to catch connection issues.
  3. User Input Handling: User input is sanitized to prevent XSS attacks.
  4. Prepared Statements: We use prepared statements to securely query the database, which helps prevent SQL injection.
  5. Password Verification: The password is verified using password_verify(), ensuring that the stored password hash is compared securely.
  6. Session Variables: Upon successful login, session variables are created to maintain user state.
  7. Error Handling: Comprehensive error handling is included to manage potential issues gracefully.

This code provides a solid foundation for a secure login system in PHP, ensuring both security and user experience are prioritized. This is a perfect foundation to start your next project or enhance your current one.

Danno
Danno

I’ve been designing web applications—on and off—since 2001, back when animated GIFs were all the rage and ‘responsive design’ meant answering your client’s emails. Over the past 14 years, I’ve kept pace with the ever-evolving trends in PHP development, successfully delivering a variety of projects that made my clients happy (and kept me caffeinated).

This website serves as my soapbox—a place to share the insights I’ve picked up along the way with anyone curious enough to dive in. Welcome aboard!

Need some custom work done? Or, just want to reach out? Email: dan@danoriordan.com

Tagged: code free login mysqli oop php prepared security snippet

Post navigation

Previous: Get total count of blog posts using MySQLi Prepared Statements
Next: Basics of PHP Coding: A Short Tutorial

One thought on “Secure Login using MySQLi”

  1. infiniti-salon.com says:
    January 4, 2025 at 1:03 AM

    I loved how this article simplified a complex topic! The site’s overall organization makes
    finding great articles easy.

    Log in to Reply

Leave a Reply Cancel reply

You must be logged in to post a comment.

Related Topics

Securing Your CodeIgniter Application Against SQL Attacks

Danno2 years ago 0
Application Installer

Creating a Web Application Installer with PHP PDO, MySQL, JavaScript, and Bootstrap

Danno2 years ago 0
Wordpress

Criteria for Creating a WordPress Plugin Using PHP 8

Danno2 years ago 0

Create a simple but secure Contact Form with PHP and Javascript

Danno2 years ago2 years ago 0
Admin Photo

Hi, I am Dan. I’ve been designing web applications—on and off—since 2001, back when animated GIFs were all the rage and ‘responsive design’ meant answering your client’s emails. Over the past 14 years, I’ve kept pace with the ever-evolving trends in PHP development, successfully delivering a variety of projects that made my clients happy (and kept me caffeinated). This website serves as my soapbox—a place to share the insights I’ve picked up along the way with anyone curious enough to dive in. Welcome aboard! Want some custom work done? Pop me an email.

Email: dan@danoriordan.com

Recent Posts

  • Turning Your Website into a Fully Functional and Secure Android and iOS Application
  • Securing Your CodeIgniter Application Against SQL Attacks
  • Creating a Web Application Installer with PHP PDO, MySQL, JavaScript, and Bootstrap
  • Create a fun card game in Python
  • Criteria for Creating a WordPress Plugin Using PHP 8

Recent Comments

  1. infiniti-salon.com on Secure Login using MySQLi

Archives

  • February 2025
  • January 2025
  • December 2024
  • November 2024
  • October 2024

Categories

  • C#
  • C++
  • Codeigniter
  • CSS
  • Development
  • HTML
  • Javascript
  • PHP
  • Python
  • Visual Basic