How do I implement authentication and authorization in PHP?

authentication, authorization, PHP, PHP security, user management, web application security
This guide demonstrates how to implement authentication and authorization in PHP for securing web applications and managing user access levels.
<?php // Start session and include database connection session_start(); $pdo = new PDO('mysql:host=localhost;dbname=test', 'username', 'password'); // User registration function register($username, $password) { global $pdo; $hashedPassword = password_hash($password, PASSWORD_DEFAULT); $stmt = $pdo->prepare("INSERT INTO users (username, password) VALUES (?, ?)"); return $stmt->execute([$username, $hashedPassword]); } // User login function login($username, $password) { global $pdo; $stmt = $pdo->prepare("SELECT * FROM users WHERE username = ?"); $stmt->execute([$username]); $user = $stmt->fetch(); if ($user && password_verify($password, $user['password'])) { $_SESSION['user_id'] = $user['id']; return true; } return false; } // Check if user is logged in function isLoggedIn() { return isset($_SESSION['user_id']); } // Authorization check function isAdmin() { global $pdo; if (!isLoggedIn()) return false; $stmt = $pdo->prepare("SELECT role FROM users WHERE id = ?"); $stmt->execute([$_SESSION['user_id']]); $user = $stmt->fetch(); return $user['role'] === 'admin'; } // Example usage if ($_SERVER['REQUEST_METHOD'] === 'POST') { if (isset($_POST['register'])) { register($_POST['username'], $_POST['password']); } elseif (isset($_POST['login'])) { if (login($_POST['username'], $_POST['password'])) { echo "Logged in successfully."; } else { echo "Login failed."; } } } ?>

authentication authorization PHP PHP security user management web application security