Tutorials Logic, IN info@tutorialslogic.com

PHP Authentication and Authorization: Login Sessions, Roles, and Ownership

Identity and Permission

Authentication establishes who is making a request. Authorization decides whether that identity may perform the requested action on the specific resource. A valid login must never be treated as permission for every record or operation.

After this lesson, you can trace registration through login and logout, rotate the session at privilege change, enforce role and ownership rules, and return a response that does not reveal whether another user owns a hidden record.

Account Lifecycle

  • Registration validates canonical email data and stores password_hash() output.
  • Login fetches by canonical identifier and calls password_verify().
  • Successful login rotates the session identifier before setting authenticated state.
  • Protected requests load the current identity and run authorization for the requested action.
  • Logout clears authenticated state, expires the session cookie, and redirects.

Login Verification

Use one generic failure message for an unknown email and an incorrect password. Keep timing and logging decisions consistent enough that the response does not become an account-discovery feature.

Verify a Stored Hash

Verify a Stored Hash
<?php
$storedHash = password_hash('learn PHP safely', PASSWORD_DEFAULT);
$candidate = 'learn PHP safely';

if (!password_verify($candidate, $storedHash)) {
    throw new RuntimeException('Invalid credentials.');
}

echo 'Credentials valid';
Output
Credentials valid

A real handler obtains the hash from a prepared database query and never stores the original password.

Session Elevation

Start the session with secure cookie settings and strict mode. Regenerate the identifier when authentication elevates privileges, then write only the minimal identity and session timestamps needed by the application.

Mark a Successful Login

Mark a Successful Login
<?php
session_start();
session_regenerate_id();

$_SESSION['user_id'] = 42;
$_SESSION['authenticated_at'] = time();

Large profile records should remain in the database; the session stores a stable identity and bounded security state.

Permission Checks

Centralize authorization as a policy or focused function. Check the requested action and resource, not just a broad role name. Ownership checks belong in both the query boundary and the authorization decision.

Authorize an Edit

Authorize an Edit
<?php
function canEditPost(int $actorId, string $role, int $ownerId): bool
{
    return $role === 'admin' || $actorId === $ownerId;
}

echo canEditPost(7, 'member', 7) ? 'Allowed' : 'Denied';
Output
Allowed

The policy makes the admin exception and ownership rule visible and testable.

Protected Failure

  • Use 401 when authentication is required and 403 when an authenticated identity lacks permission.
  • For private resources, a 404 can avoid confirming that another user record exists.
  • Apply CSRF protection to state-changing browser requests even after authorization.
  • Rate-limit login and recovery endpoints without permanently locking an account through attacker activity.

Separate Identity from Access

0 of 2 checked

Q1. What does authentication establish?

Q2. When should the session ID change?

Try this next

Protect One Resource

0 of 2 completed

  1. Map validation, prepared lookup, password verification, session rotation, logging, and redirect behavior.
  2. Assert owner, another member, administrator, anonymous user, and missing-resource outcomes.
Browse Free Tutorials

Explore 500+ free tutorials across 20+ languages and frameworks.