Creating a PHP MySQL login page
A login system is fundamental to websites requiring user accounts.
PHP MySQL Login Page

Login Page in PHP + MySQL
Creating a PHP MySQL login page is a common yet essential task for any web developer 🪄.
Login pages serve as gateways to secure parts of websites or applications, providing user authentication and access control.
This article provides an in-depth, step-by-step 🎊 guide on how to create a functional and secure PHP MySQL login page, covering everything from setup to advanced security practices.
Table of Contents
1. Introduction to PHP MySQL Login Systems 2. Setting Up the Development Environment ∘ 2.1 Install XAMPP ∘ 2.2 Create a New Project Folder 3. Database Design for User Authentication ∘ 3.1 Creating the Database and Table ∘ 3.2 Setting Up Database Credentials in PHP 4. Creating the User Login Form 5. PHP Script for Processing Login 6. Securing User Passwords with Hashing ∘ 6.1 Registering Users with Password Hashing 7. Implementing Sessions to Maintain Login State ∘ 7.1 Starting a Session on Login ∘ 7.2 Verifying Session for Secure Pages 8. Error Handling and Validation ∘ 8.1 Validating User Inputs ∘ 8.2 Handling Errors 9. Advanced Security Techniques ∘ 9.1 SQL Injection Prevention ∘ 9.2 Rate Limiting and Brute Force Protection ∘ 9.3 HTTPS Encryption 10. Testing and Troubleshooting ∘ 10.1 Testing Login and Registration ∘ 10.2 Debugging Common Issues 11. Conclusion
1. Introduction to PHP MySQL Login Systems
A login system is fundamental to websites requiring user accounts.
A robust login system:
- Verifies user credentials.
- Keeps user data safe.
- Maintains login state across pages.
PHP is well-suited for creating login systems because it integrates seamlessly with MySQL, providing an efficient solution for managing user accounts and authentication.
2. Setting Up the Development Environment
For this tutorial, we’ll use:
- XAMPP or MAMP as a local development server.
- PHP 7 or 8.
- MySQL as the database for storing user data.
Ensure your environment is correctly configured to handle PHP and MySQL.
[embed]What Are the New Features in PHP 8? medium.com
2.1 Install XAMPP
- Download and install XAMPP.
- Start Apache and MySQL from the XAMPP control panel.
2.2 Create a New Project Folder
- Navigate to the
htdocsdirectory in your XAMPP folder. - Create a new folder for your project (e.g.,
php_login). - Open your project folder in a code editor like VS Code.
[embed]Boost Your Coding Productivity: Top 5 Must-Have VS Code Extensions blog.stackademic.com
3. Database Design ⚓️ for User Authentication
Create a MySQL database and table to store user information.
3.1 Creating the Database and Table
- Open PHPMyAdmin (http://localhost/phpmyadmin).
- Create a new database called
login_db. - Within
login_db, create a table nameduserswith the following structure:

Database Table
This structure allows us to store unique usernames, securely hashed passwords, and emails for account recovery.
3.2 Setting Up Database Credentials in PHP
Create a config.php file in your project folder to handle database connection details.
<?php
$host = 'localhost';
$db = 'login_db';
$user = 'root';
$pass = '';
try {
$pdo = new PDO("mysql:host=$host;dbname=$db", $user, $pass);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
die("Could not connect to the database $db :" . $e->getMessage());
}
?>
[embed]Are You Using PHP MySQL Prepared Statements for Protection? medium.com
4. Creating the User Login Form
Create an HTML file named login.php with a form for users to enter their credentials.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Login</title>
</head>
<body>
<h2>Login</h2>
<form action="authenticate.php" method="post">
<label for="username">Username:</label>
<input type="text" name="username" required><br><br>
<label for="password">Password:</label>
<input type="password" name="password" required><br><br>
<input type="submit" value="Login">
</form>
</body>
</html>
5. PHP Script for Processing Login 🎉
Create authenticate.php to handle login logic, verify credentials, and start user sessions.
<?php
session_start();
require 'config.php';
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$username = $_POST['username'];
$password = $_POST['password'];
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username");
$stmt->bindParam(':username', $username);
$stmt->execute();
$user = $stmt->fetch(PDO::FETCH_ASSOC);
if ($user && password_verify($password, $user['password_hash'])) {
$_SESSION['user_id'] = $user['id'];
$_SESSION['username'] = $user['username'];
header("Location: welcome.php");
exit;
} else {
echo "Invalid username or password.";
}
}
?>
[embed]Are You Using PHP Sessions Correctly? Common Mistakes to Avoid medium.com
6. Securing User 📝 Passwords with Hashing
Always use hashing to store passwords securely. In PHP, the password_hash function creates a secure hash for storing passwords, while password_verify checks passwords during login.
6.1 Registering Users with Password Hashing
Add a register.php file to allow users to create accounts with securely hashed passwords.
<?php
require 'config.php';
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$username = $_POST['username'];
$password = password_hash($_POST['password'], PASSWORD_BCRYPT);
$stmt = $pdo->prepare("INSERT INTO users (username, password_hash) VALUES (:username, :password_hash)");
$stmt->bindParam(':username', $username);
$stmt->bindParam(':password_hash', $password);
if ($stmt->execute()) {
echo "Registration successful!";
} else {
echo "Error: Could not register user.";
}
}
?>
[embed]Is Password Hashing Really Necessary? Debunking Common Myths blog.stackademic.com
7. 🧑🏽💻 Implementing Sessions to Maintain Login State
Sessions allow us to remember the logged-in state across pages.
7.1 Starting a Session on Login
As seen in authenticate.php, a session is started to store user information.
7.2 Verifying Session for Secure Pages
Create a welcome.php file to welcome authenticated users:
<?php
session_start();
if (!isset($_SESSION['user_id'])) {
header("Location: login.php");
exit;
}
echo "Welcome, " . $_SESSION['username'];
?>
8. Error 🚫 Handling and Validation
To prevent invalid data, validate inputs and handle errors appropriately.
8.1 Validating User Inputs
Add input validation to register.php and authenticate.php.
$username = filter_var($_POST['username'], FILTER_SANITIZE_STRING);
$password = filter_var($_POST['password'], FILTER_SANITIZE_STRING);
8.2 Handling Errors
In authenticate.php, provide feedback for invalid login attempts.
9. Advanced Security 🔑 Techniques
Enhancing security ensures that sensitive data remains safe.
9.1 SQL Injection Prevention
Use prepared statements to prevent SQL injection. For instance:
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username");
9.2 Rate Limiting and Brute Force Protection
Implement account lockouts or CAPTCHA to prevent brute force attacks.
9.3 HTTPS Encryption
Encrypt data transmission by enabling HTTPS.
[embed]Why PHP is Better Than Other Server-side Languages? medium.com
10. Testing and Troubleshooting 🔎
Testing each component helps identify errors and ensures proper functionality.
10.1 Testing Login and Registration
Test cases should include:
- Correct login.
- Incorrect username or password.
- Empty fields.
10.2 Debugging Common Issues
Check for common errors like incorrect SQL queries or session configuration issues.
11. Conclusion
Creating a PHP MySQL login page is a foundational skill for web developers.
By understanding the setup, database design, session handling, and security best practices, you can build a reliable, secure login system that protects user data and enhances user experience.
Thank you for reading until the end. Before you go:
Be sure to clap and follow the writer ️👏️️
Follow me: https://medium.com/@mayurkoshti12
메타데이터
- post_id
- ca8b157dc768
- slug
- creating-a-php-mysql-login-page-ca8b157dc768
- url
- https://towardsdev.com/creating-a-php-mysql-login-page-ca8b157dc768
- canonical_url
- https://towardsdev.com/creating-a-php-mysql-login-page-ca8b157dc768
- author_url
- https://medium.com/@mayurkoshti12
- status
- ok
- fetched_at
- 2026-08-12 08:09:52