Authentication and Authorization

📘 PHP 👁 26 views 📅 Dec 22, 2025
⏱ Estimated reading time: 2 min

Introduction

Authentication and Authorization are core security concepts used to control access to web applications.

  • AuthenticationWho are you? (Login / Identity verification)

  • AuthorizationWhat are you allowed to do? (Permissions / Access control)


Authentication

What is Authentication?

Authentication verifies the identity of a user, usually using username & password, OTP, or tokens.


Common Authentication Methods

  • Username & Password

  • Email & Password

  • OTP (One-Time Password)

  • Token-based Authentication (JWT)

  • OAuth (Google, Facebook login)


Basic Login Authentication (PHP Example)

Login Form (HTML)

<form method="post"> <input type="email" name="email" placeholder="Email"> <input type="password" name="password" placeholder="Password"> <input type="submit" name="login"> </form>

PHP Authentication Logic

session_start(); if (isset($_POST['login'])) { $email = $_POST['email']; $password = $_POST['password']; // Fetch user from database $stmt = $pdo->prepare("SELECT * FROM users WHERE email = ?"); $stmt->execute([$email]); $user = $stmt->fetch(); if ($user && password_verify($password, $user['password'])) { $_SESSION['user_id'] = $user['id']; $_SESSION['role'] = $user['role']; header("Location: dashboard.php"); } else { echo "Invalid login credentials"; } }

Authorization

What is Authorization?

Authorization determines what an authenticated user can access or perform within the system.


Role-Based Authorization

Common roles:

  • Admin

  • Editor

  • User


Authorization Example (Role Check)

session_start(); if ($_SESSION['role'] !== 'admin') { die("Access denied"); }

Authentication vs Authorization

FeatureAuthenticationAuthorization
PurposeVerify identityGrant permissions
QuestionWho are you?What can you do?
Happens whenLoginAfter login
Depends onCredentialsRoles & permissions

Session-Based Authentication

  • Stores user identity in session

  • Common in PHP applications

$_SESSION['user_id'] = $user['id'];

Token-Based Authentication (Overview)

Used in APIs and mobile apps.

  • JWT (JSON Web Token)

  • Stateless authentication

  • Sent via headers


Logout Functionality

session_start(); session_destroy(); header("Location: login.php");

Security Best Practices

  • Hash passwords using password_hash()

  • Use HTTPS

  • Regenerate session ID after login

  • Implement CSRF protection

  • Limit login attempts

  • Validate user input


Common Use Cases

  • User login systems

  • Admin panels

  • Role-based dashboards

  • API security



🔒 Some advanced sections are available for Registered Members
Register Now

Share this Post


← Back to Tutorials

Popular Competitive Exam Quizzes