In this chapter, we will dive into user authentication and session management in PHP. This includes creating a login page, managing sessions, handling logouts, introducing cookies, and redirecting pages. Think of this as building a secure entry system for your digital museum, where only authorized visitors can access certain areas.
Step 1: Setting Up the Environment
Ensure you have a working environment with PHP and MySQL set up. We’ll create a simple user authentication system with a login and logout functionality.
First, create a database and a users table to store user credentials.
SQL
Copy code
CREATE DATABASE user_management;
USE user_management;
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(50) NOT NULL UNIQUE,
password VARCHAR(255) NOT NULL
);
INSERT INTO users (username, password) VALUES
(‘admin’, ‘$2y$10$WzH/q9TvkhO92eB.k7B8ue4jeVRRTY7jbWnce7xxEr5EIKD1S/WPC’); — password is ‘password’
The password is hashed using password_hash(‘password’, PASSWORD_BCRYPT). Always hash passwords for security.
Step 2: Creating the Login Page
Create a file named login.php for the login form and authentication logic.
php
Copy code
<?php
session_start();
$servername = “localhost”;
$username = “root”;
$password = “”;
$dbname = “user_management”;
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die(“Connection failed: ” . $conn->connect_error);
}
if ($_SERVER[“REQUEST_METHOD”] == “POST”) {
$username = $_POST[‘username’];
$password = $_POST[‘password’];
$sql = “SELECT * FROM users WHERE username = ‘$username'”;
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$row = $result->fetch_assoc();
if (password_verify($password, $row[‘password’])) {
$_SESSION[‘username’] = $username;
header(“Location: welcome.php”);
exit();
} else {
echo “Invalid password.”;
}
} else {
echo “No user found.”;
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Login</title>
</head>
<body>
<form method=”post” action=””>
Username: <input type=”text” name=”username” required><br>
Password: <input type=”password” name=”password” required><br>
<button type=”submit”>Login</button>
</form>
</body>
</html>
Step 3: Creating the Welcome Page
Create a file named welcome.php that only logged-in users can access.
php
Copy code
<?php
session_start();
if (!isset($_SESSION[‘username’])) {
header(“Location: login.php”);
exit();
}
echo “Welcome, ” . $_SESSION[‘username’];
?>
<!DOCTYPE html>
<html>
<head>
<title>Welcome</title>
</head>
<body>
<p>You are logged in.</p>
<a href=”logout.php”>Logout</a>
</body>
</html>
Step 4: Creating the Logout Page
Create a file named logout.php to handle logging out and destroying the session.
php
Copy code
<?php
session_start();
session_unset();
session_destroy();
header(“Location: login.php”);
exit();
?>
Step 5: Handling Session Timeout and Cookies
To enhance security, we can implement a session timeout and use cookies for session management.
Session Timeout:
In the login.php and welcome.php scripts, add a session timeout mechanism.
php
Copy code
// login.php and welcome.php
session_start();
$timeout_duration = 1800; // 30 minutes
if (isset($_SESSION[‘LAST_ACTIVITY’]) && (time() – $_SESSION[‘LAST_ACTIVITY’]) > $timeout_duration) {
session_unset();
session_destroy();
header(“Location: login.php”);
exit();
}
$_SESSION[‘LAST_ACTIVITY’] = time();
Using Cookies:
To remember the user, we can set a cookie during login.
php
Copy code
// login.php
if ($_SERVER[“REQUEST_METHOD”] == “POST”) {
$username = $_POST[‘username’];
$password = $_POST[‘password’];
$sql = “SELECT * FROM users WHERE username = ‘$username'”;
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$row = $result->fetch_assoc();
if (password_verify($password, $row[‘password’])) {
$_SESSION[‘username’] = $username;
// Set a cookie that expires in 30 days
setcookie(“username”, $username, time() + (86400 * 30), “/”);
header(“Location: welcome.php”);
exit();
} else {
echo “Invalid password.”;
}
} else {
echo “No user found.”;
}
}
// welcome.php
if (isset($_COOKIE[‘username’]) && !isset($_SESSION[‘username’])) {
$_SESSION[‘username’] = $_COOKIE[‘username’];
}
In this chapter, you’ve learned how to create a secure login and logout system using PHP sessions and cookies. You also implemented a session timeout for enhanced security and user experience. This setup ensures that only authenticated users can access certain areas of your web application, maintaining the integrity and confidentiality of your data. Keep practicing, and soon you’ll master session management and user authentication in PHP. Happy coding!