Setting up a login and logout system in PHP is straightforward, making it an ideal project for beginners. This guide will walk you through the steps to create a basic authentication system. We will create four files and a MySQL table to handle the user login and logout functionality.
Files Overview
login.php
authenticate.php
index.php
logout.php
MySQL Table Creation
First, we need to create a MySQL table to store user data. Use the following SQL script to create a users
table:
CREATE TABLE IF NOT EXISTS `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(50) NOT NULL,
`password` varchar(150) NOT NULL,
`name` varchar(50) NOT NULL,
`active` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM;
Step 1: Creating the Login Form (login.php
)
We start by creating a login form where users can input their username and password.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Login</title>
</head>
<body>
<form action="authenticate.php" method="post">
<table width="100%" cellpadding="4" cellspacing="0" border="0">
<tr>
<td>Username:</td>
<td><input type="text" name="username" required></td>
</tr>
<tr>
<td>Password:</td>
<td><input type="password" name="password" required></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Login"></td>
</tr>
</table>
</form>
</body>
</html>
Explanation
- Form Action: The form’s action is set to
authenticate.php
, which means the data will be submitted toauthenticate.php
for processing. - Input Fields: Two fields are created for username and password. Both fields are required for submission.
- Submit Button: A submit button is provided to send the form data.
Step 2: Authenticating the User (authenticate.php
)
This file will handle the authentication logic.
<?php
session_start();
$conn = new mysqli('localhost', 'root', 'pass', 'test');
if ($conn->connect_error) {
die('Connection failed: ' . $conn->connect_error);
}
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$username = trim($_POST['username']);
$password = trim($_POST['password']);
if ($username != '') {
$stmt = $conn->prepare("SELECT * FROM users WHERE username = ? AND active = 1");
$stmt->bind_param('s', $username);
$stmt->execute();
$result = $stmt->get_result();
$user = $result->fetch_assoc();
if ($user && password_verify($password, $user['password'])) {
$_SESSION['user_id'] = $user['id'];
$_SESSION['username'] = $user['username'];
header('Location: index.php');
exit;
} else {
header('Location: login.php?err=1');
exit;
}
}
}
?>
Explanation
- Session Start: We start a session to store user data upon successful login.
- Database Connection: A connection to the MySQL database is established.
- POST Check: We check if the form was submitted via POST.
- User Validation: We retrieve the user record from the database and verify the password using
password_verify()
. - Session Variables: If the user is authenticated, their ID and username are stored in session variables.
- Redirection: Upon successful authentication, the user is redirected to
index.php
. If authentication fails, the user is redirected back to the login page with an error.
Step 3: Creating the Index Page (index.php
)
This page is accessible only to logged-in users.
<?php
session_start();
if (!isset($_SESSION['user_id'])) {
header('Location: login.php');
exit;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Home</title>
</head>
<body>
<p>You are now logged in</p>
<a href="logout.php">Logout</a>
</body>
</html>
Explanation
- Session Check: We check if the user ID is set in the session. If not, the user is redirected to the login page.
- Logged In Message: A simple message is displayed indicating that the user is logged in.
- Logout Link: A link is provided to log out.
Step 4: Creating the Logout Script (logout.php
)
This script handles the user logout process.
<?php
session_start();
session_unset();
session_destroy();
header('Location: login.php');
exit;
?>
Explanation
- Session Handling: The session is started, and then all session variables are unset, and the session is destroyed.
- Redirection: The user is redirected to the login page after logging out.
Conclusion
With these steps, you have created a basic login/logout system in PHP. This system includes:
- A login form for user input.
- An authentication script to verify user credentials.
- A protected page accessible only to authenticated users.
- A logout script to end the user session.
Kamaya Bragnalo