Create A Login Page With PHP And MySQL: A Simple Guide
Hey guys! Today, we're going to walk through creating a simple login page using PHP and MySQL. This is a fundamental skill for any web developer, and it’s easier than you might think. So, buckle up, and let’s get started!
Setting Up Your Environment
Before diving into the code, let's make sure our environment is ready. You'll need a few things installed:
- A Web Server: Something like Apache (using XAMPP or WAMP) or Nginx. These servers allow you to run PHP code and serve web pages.
- PHP: Make sure PHP is installed and configured correctly on your server. A version of 7.0 or higher is recommended.
- MySQL: This is your database server. You'll need it to store user credentials. Ensure it's up and running.
- A Code Editor: VSCode, Sublime Text, or any editor you prefer for writing code.
Once you have these set up, you’re good to go. Now, let’s create our database and table.
Creating the Database and Table
First, we need a database to store our user information. Log into your MySQL server (usually through phpMyAdmin or the MySQL command-line tool) and create a new database. Let's call it user_database.
CREATE DATABASE user_database;
USE user_database;
Next, we’ll create a table to hold our user data. This table will have columns for user ID, username, and password. Here’s the SQL to create the users table:
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50) NOT NULL UNIQUE,
password VARCHAR(255) NOT NULL
);
- id: This is the primary key and auto-increments, so each user gets a unique ID.
- username: This is the username that users will use to log in. The
UNIQUEconstraint ensures that each username is unique. - password: This will store the user's password. We’ll hash this for security, so it’ll be a long string.
Now that we have our database and table, let's move on to the PHP code.
Coding the Login Page with PHP
We’ll break this down into a few parts: the HTML form for the login page, the PHP code to handle the form submission, and the PHP code to verify the user credentials.
HTML Form (login.php)
Create a file named login.php. This will contain our HTML form for users to enter their username and password.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Login Page</title>
<style>
body {
font-family: Arial, sans-serif;
background-color: #f4f4f4;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
}
.login-container {
background-color: #fff;
padding: 20px;
border-radius: 8px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
width: 300px;
text-align: center;
}
.form-group {
margin-bottom: 15px;
}
.form-group label {
display: block;
text-align: left;
margin-bottom: 5px;
}
.form-group input {
width: 100%;
padding: 8px;
border: 1px solid #ccc;
border-radius: 4px;
box-sizing: border-box;
}
.form-group button {
background-color: #4caf50;
color: white;
padding: 10px 15px;
border: none;
border-radius: 4px;
cursor: pointer;
}
.form-group button:hover {
background-color: #45a049;
}
.error-message {
color: red;
margin-top: 10px;
}
</style>
</head>
<body>
<div class="login-container">
<h2>Login</h2>
<form action="login_process.php" method="post">
<div class="form-group">
<label for="username">Username:</label>
<input type="text" id="username" name="username" required>
</div>
<div class="form-group">
<label for="password">Password:</label>
<input type="password" id="password" name="password" required>
</div>
<div class="form-group">
<button type="submit">Login</button>
</div>
</form>
<?php
if (isset($_GET['error'])) {
echo '<div class="error-message">' . htmlspecialchars($_GET['error']) . '</div>';
}
?>
</div>
</body>
</html>
This HTML code creates a simple login form with fields for username and password. It also includes a section to display any error messages.
PHP Code to Handle Form Submission (login_process.php)
Next, create a file named login_process.php. This file will handle the form submission and verify the user’s credentials against the database.
<?php
session_start();
// Database credentials
$host = "localhost";
$username = "your_db_username";
$password = "your_db_password";
$database = "user_database";
// Create connection
$conn = new mysqli($host, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Get username and password from the form
$username = $_POST['username'];
$password = $_POST['password'];
// Prepare SQL statement to prevent SQL injection
$sql = "SELECT id, username, password FROM users WHERE username = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $username);
// Execute the statement
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows == 1) {
$user = $result->fetch_assoc();
// Verify the password
if (password_verify($password, $user['password'])) {
// Start a session and store user information
$_SESSION['user_id'] = $user['id'];
$_SESSION['username'] = $user['username'];
// Redirect to a protected page
header("Location: welcome.php");
exit();
} else {
// Incorrect password
header("Location: login.php?error=Incorrect username or password");
exit();
}
} else {
// User not found
header("Location: login.php?error=Incorrect username or password");
exit();
}
// Close connection
$stmt->close();
$conn->close();
?>
In this code:
- We start a session to store user information after successful login.
- We connect to the MySQL database using the provided credentials.
- We retrieve the username and password from the form submission.
- We use a prepared statement to prevent SQL injection attacks.
- We verify the password using
password_verify(), which compares the entered password with the hashed password stored in the database. - If the credentials are correct, we store the user ID and username in the session and redirect the user to a welcome page.
- If the credentials are incorrect, we redirect the user back to the login page with an error message.
Creating a Welcome Page (welcome.php)
For a complete example, let’s create a simple welcome page that displays the logged-in user's username. Create a file named welcome.php.
<?php
session_start();
// Check if the user is logged in
if (!isset($_SESSION['user_id'])) {
header("Location: login.php");
exit();
}
$username = $_SESSION['username'];
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Welcome</title>
</head>
<body>
<h2>Welcome, <?php echo htmlspecialchars($username); ?>!</h2>
<p>You are now logged in.</p>
<a href="logout.php">Logout</a>
</body>
</html>
This page checks if the user is logged in by verifying the existence of the user_id session variable. If the user is not logged in, they are redirected to the login page. If they are logged in, the page displays a welcome message with their username.
Logout Functionality (logout.php)
Finally, let’s create a logout.php page to allow users to log out.
<?php
session_start();
// Unset all session variables
$_SESSION = array();
// Destroy the session
session_destroy();
// Redirect to login page
header("Location: login.php");
exit();
?>
This script starts the session, unsets all session variables, destroys the session, and redirects the user back to the login page.
Security Considerations
Security is paramount when dealing with user authentication. Here are a few critical points to keep in mind:
-
Password Hashing: Never store passwords in plain text. Use PHP’s
password_hash()function to hash passwords before storing them in the database. This function uses a strong hashing algorithm (bcrypt by default) to securely hash the password.$password = password_hash($_POST['password'], PASSWORD_DEFAULT); -
Prepared Statements: Always use prepared statements to prevent SQL injection attacks. Prepared statements allow you to safely insert data into SQL queries without risking malicious code injection.
$sql = "SELECT id, username, password FROM users WHERE username = ?"; $stmt = $conn->prepare($sql); $stmt->bind_param("s", $username); -
Session Security: Properly manage sessions to prevent session hijacking and fixation attacks. Use
session_regenerate_id()periodically to regenerate the session ID. -
Input Validation: Validate all user inputs to prevent cross-site scripting (XSS) and other attacks. Use functions like
htmlspecialchars()to escape potentially malicious characters. -
HTTPS: Always use HTTPS to encrypt the communication between the client and the server, protecting sensitive data like usernames and passwords from eavesdropping.
Complete Example: User Registration
To make this guide more comprehensive, let’s add user registration functionality. We’ll create a register.php page with a form for users to enter their desired username and password, and a register_process.php file to handle the registration process.
HTML Form (register.php)
Create a file named register.php with the following code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Register</title>
<style>
body {
font-family: Arial, sans-serif;
background-color: #f4f4f4;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
}
.register-container {
background-color: #fff;
padding: 20px;
border-radius: 8px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
width: 300px;
text-align: center;
}
.form-group {
margin-bottom: 15px;
}
.form-group label {
display: block;
text-align: left;
margin-bottom: 5px;
}
.form-group input {
width: 100%;
padding: 8px;
border: 1px solid #ccc;
border-radius: 4px;
box-sizing: border-box;
}
.form-group button {
background-color: #4caf50;
color: white;
padding: 10px 15px;
border: none;
border-radius: 4px;
cursor: pointer;
}
.form-group button:hover {
background-color: #45a049;
}
.error-message {
color: red;
margin-top: 10px;
}
</style>
</head>
<body>
<div class="register-container">
<h2>Register</h2>
<form action="register_process.php" method="post">
<div class="form-group">
<label for="username">Username:</label>
<input type="text" id="username" name="username" required>
</div>
<div class="form-group">
<label for="password">Password:</label>
<input type="password" id="password" name="password" required>
</div>
<div class="form-group">
<button type="submit">Register</button>
</div>
</form>
<?php
if (isset($_GET['error'])) {
echo '<div class="error-message">' . htmlspecialchars($_GET['error']) . '</div>';
}
?>
</div>
</body>
</html>
PHP Code to Handle Registration (register_process.php)
Create a file named register_process.php with the following code:
<?php
// Database credentials
$host = "localhost";
$username = "your_db_username";
$password = "your_db_password";
$database = "user_database";
// Create connection
$conn = new mysqli($host, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Get username and password from the form
$username = $_POST['username'];
$password = $_POST['password'];
// Hash the password
$hashed_password = password_hash($password, PASSWORD_DEFAULT);
// Prepare SQL statement to prevent SQL injection
$sql = "INSERT INTO users (username, password) VALUES (?, ?)";
$stmt = $conn->prepare($sql);
$stmt->bind_param("ss", $username, $hashed_password);
// Execute the statement
if ($stmt->execute()) {
// Registration successful
header("Location: login.php");
exit();
} else {
// Registration failed
header("Location: register.php?error=Registration failed");
exit();
}
// Close connection
$stmt->close();
$conn->close();
?>
This code:
- Connects to the MySQL database.
- Retrieves the username and password from the registration form.
- Hashes the password using
password_hash(). - Uses a prepared statement to insert the username and hashed password into the
userstable. - Redirects the user to the login page upon successful registration or displays an error message if registration fails.
Conclusion
And there you have it! You’ve successfully created a basic login page with PHP and MySQL, complete with registration functionality. Remember to always prioritize security by hashing passwords, using prepared statements, and validating user inputs. This is just the beginning, though. There's a lot more to learn about web development, but you've got a solid foundation now. Keep practicing, keep learning, and you’ll be building amazing web applications in no time! Happy coding, guys!