PHP - MySQL Login: A Guide for Beginners
Hello there, aspiring web developers! Today, we're going to begin an exciting journey into the world of PHP and MySQL to create a simple yet powerful login system. As someone who has been teaching this for years, I can tell you that mastering this skill is like unlocking a secret door in the world of web development. So, let's roll up our sleeves and dive in!
Understanding the Overall Picture
Before we start coding, let's take a moment to understand what we're aiming to achieve. Imagine you're building a treehouse. You need a strong foundation, walls, a roof, and a way to get in and out. Our PHP-MySQL login system is similar:
- Config.php: This is our foundation, connecting us to the database.
- Login.php: Think of this as the door to our treehouse.
- Session.php: This keeps track of who's inside the treehouse.
- Welcome.php: The cozy interior where authorized users spend time.
- Logout.php: The exit sign, guiding users out.
Now, let's construct each part step by step!
Config.php: Establishing the Foundation
This file is like the secret handshake between PHP and MySQL. It's where we store our database connection details.
<?php
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', '');
define('DB_NAME', 'login_demo');
$conn = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_NAME);
if($conn === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
?>
Let's break this down:
- We use
define()
to set constants for our database details. -
mysqli_connect()
establishes the connection to our MySQL database. - If the connection fails, we use
die()
to halt execution and display an error message.
Pro tip: Never share your actual database credentials! This example uses default values, but in a real project, keep these secret!
Login.php: The Gatekeeper
This is where the magic happens. Users enter their credentials, and we check if they're allowed in.
<?php
session_start();
require_once "config.php";
if($_SERVER["REQUEST_METHOD"] == "POST"){
$username = trim($_POST["username"]);
$password = trim($_POST["password"]);
$sql = "SELECT id, username, password FROM users WHERE username = ?";
if($stmt = mysqli_prepare($conn, $sql)){
mysqli_stmt_bind_param($stmt, "s", $param_username);
$param_username = $username;
if(mysqli_stmt_execute($stmt)){
mysqli_stmt_store_result($stmt);
if(mysqli_stmt_num_rows($stmt) == 1){
mysqli_stmt_bind_result($stmt, $id, $username, $hashed_password);
if(mysqli_stmt_fetch($stmt)){
if(password_verify($password, $hashed_password)){
session_start();
$_SESSION["loggedin"] = true;
$_SESSION["id"] = $id;
$_SESSION["username"] = $username;
header("location: welcome.php");
} else{
$login_err = "Invalid username or password.";
}
}
} else{
$login_err = "Invalid username or password.";
}
} else{
echo "Oops! Something went wrong. Please try again later.";
}
mysqli_stmt_close($stmt);
}
mysqli_close($conn);
}
?>
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="UTF-8">
<title>Login</title>
</head>
<body>
<h2>Login</h2>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<div>
<label>Username</label>
<input type="text" name="username" required>
</div>
<div>
<label>Mot de passe</label>
<input type="password" name="password" required>
</div>
<div>
<input type="submit" value="Login">
</div>
</form>
</body>
</html>
Wow, that's a lot to take in! Let's break it down:
- We start the session and include our config file.
- We check if the form was submitted using POST.
- We use prepared statements to prevent SQL injection (a common security vulnerability).
- We verify the password using
password_verify()
(always hash passwords in real projects!). - If login is successful, we set session variables and redirect to welcome.php.
- We also have a simple HTML form for users to enter their credentials.
Remember, in real-world applications, you'd want to add more security measures and error handling!
Session.php: The Bouncer
This file checks if a user is logged in. If not, it sends them back to the login page.
<?php
session_start();
if(!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true){
header("location: login.php");
exit;
}
?>
Short and sweet! This code:
- Starts the session.
- Checks if the user is logged in.
- If not, it redirects them to the login page.
Welcome.php: The VIP Area
This is where users end up after successfully logging in.
<?php
require_once "session.php";
?>
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="UTF-8">
<title>Welcome</title>
</head>
<body>
<h1>Salut, <b><?php echo htmlspecialchars($_SESSION["username"]); ?></b>. Bienvenue sur notre site.</h1>
<p>
<a href="logout.php">Déconnexion</a>
</p>
</body>
</html>
Here's what's happening:
- We include session.php to ensure only logged-in users can access this page.
- We display a personalized welcome message using the username stored in the session.
- We provide a link to log out.
Logout.php: The Exit
Finally, we need a way for users to log out securely.
<?php
session_start();
$_SESSION = array();
session_destroy();
header("location: login.php");
exit;
?>
This script:
- Starts the session.
- Unsets all session variables.
- Destroys the session.
- Redirects the user back to the login page.
Putting It All Together
Now that we've built all the pieces, let's summarize how they work together:
File | Purpose | Key Functions |
---|---|---|
Config.php | Database connection | mysqli_connect() |
Login.php | User authentication | mysqli_prepare(), password_verify() |
Session.php | Session management | session_start(), $_SESSION checks |
Welcome.php | Authorized user page | Displays personalized content |
Logout.php | End user session | session_destroy() |
And there you have it! You've just built a basic PHP-MySQL login system. Remember, this is just the beginning. In real-world applications, you'd want to add more features like:
- Password reset functionality
- Remember me option
- More robust error handling
- Enhanced security measures
Keep practicing, stay curious, and before you know it, you'll be building complex web applications with ease. Happy coding, future web wizards!
Credits: Image by storyset