Authorization and Authentication in PHP: A Complete Guide with Examples

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Authorization and Authentication in PHP: From Basics to Security



In modern web development, authentication (verifying user identity) and authorization (checking access rights) are fundamental security mechanisms. In PHP, these processes are implemented through working with sessions, cookies, password hashing, and tokens. In this article, we will cover all key aspects necessary for creating a secure login system on the educational website pythonlib.ru.



1. Basic Concepts: Authentication vs Authorization



Before writing code, it is important to clearly distinguish between the two terms:



  • Authentication — the process of verifying that a user is who they claim to be (login + password, biometrics, token).
  • Authorization — determining which resources and actions are available to an authenticated user (roles: admin, moderator, user).


In PHP, authentication is typically performed via sessions or JWT, while authorization is done by checking roles in the database.



2. Password Hashing: Never Store Passwords in Plain Text



PHP provides built-in functions for secure password hashing. Use password_hash() and password_verify() — this is the modern standard.



// User registration$password = $_POST['password'];$hashedPassword = password_hash($password, PASSWORD_BCRYPT, ['cost' => 12]);

// Save $hashedPassword to the database$sql = "INSERT INTO users (email, password_hash) VALUES (?, ?)";$stmt = $pdo->prepare($sql);$stmt->execute([$_POST['email'], $hashedPassword]);


// Verification during login$inputPassword = $_POST['password'];$storedHash = $user['password_hash']; // from DB

if (password_verify($inputPassword, $storedHash)) { // Authentication successful $_SESSION['user_id'] = $user['id'];} else { // Incorrect password}


3. Session Management in PHP



Sessions are the most common way to track authenticated users. PHP automatically generates a unique session ID and stores it in a cookie.



// Start session (always at the beginning of the script)session_start();

// After successful login$_SESSION['user_id'] = $user['id'];$_SESSION['user_role'] = $user['role']; // for authorization$_SESSION['logged_in'] = true;

// Check authentication on protected pagesfunction requireAuth() { if (!isset($_SESSION['logged_in']) || $_SESSION['logged_in'] !== true) { header('Location: /login.php'); exit; }}

// Logoutsession_destroy();setcookie(session_name(), '', time() - 3600, '/');


4. Session Security: Protection Against Attacks



To prevent Session Hijacking and Session Fixation, use the following measures:



  • Regenerate session ID after login:


session_regenerate_id(true); // deletes the old session


  • Check User-Agent and IP (optional, but increases security):


$_SESSION['user_agent'] = $_SERVER['HTTP_USER_AGENT'];

// On each requestif ($_SESSION['user_agent'] !== $_SERVER['HTTP_USER_AGENT']) { session_destroy(); die('Suspicious activity');}


  • Set session cookie flags in php.ini or via session_set_cookie_params():


session_set_cookie_params([    'lifetime' => 0,           // until browser is closed    'secure' => true,          // HTTPS only    'httponly' => true,        // inaccessible from JavaScript    'samesite' => 'Strict'     // CSRF protection]);session_start();


5. JWT (JSON Web Tokens)

Recommendations