User login is one of the most fundamental and common features in modern website development. This article will show you how to create a simple user login system using PHP, from database creation to writing the login logic. This tutorial is suitable for PHP beginners to learn and reference.
First, you need to create a database to store user login information. You can use phpMyAdmin or any other database management tool to create a database named login_system.
CREATE DATABASE login_system;
Next, create a table named users in the login_system database to store the user's login information.
USE login_system;
CREATE TABLE users (
id INT(11) AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(255) NOT NULL,
password VARCHAR(255) NOT NULL
);
In your HTML page, create a simple login form where users can input their username and password to log in.
<form method="POST" action="login.php">
<input type="text" name="username" placeholder="Username" required>
<input type="password" name="password" placeholder="Password" required>
<input type="submit" value="Log In">
</form>
When the user submits the login form, you'll need to write PHP code to handle the login request and validate the username and password.
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$username = $_POST["username"];
$password = $_POST["password"];
// Validate username and password
// In a real-world application, you should query the database
$db_username = "admin";
$db_password = "password";
if ($username == $db_username && $password == $db_password) {
echo "Login successful!";
} else {
echo "Invalid username or password!";
}
}
?>
In the code above, we use the $_POST superglobal array to retrieve the username and password entered by the user and compare them with the data stored in the database. The comparison logic here is just an example; in actual development, you should query the database for verification based on your requirements.
This article demonstrated how to implement a basic user login system using PHP through a simple example. The login functionality involves submitting a username and password through a form, which is then verified with PHP code. While the code provided is a basic example, it can serve as a foundation for beginners to understand PHP login systems. In actual projects, further improvements should be made, such as enhancing password storage and security.
We hope this tutorial helps readers understand and implement PHP login functionality, laying the groundwork for more advanced features in the future.