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.
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.
<?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';
Credentials valid
A real handler obtains the hash from a prepared database query and never stores the original password.
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.
<?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.
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.
<?php
function canEditPost(int $actorId, string $role, int $ownerId): bool
{
return $role === 'admin' || $actorId === $ownerId;
}
echo canEditPost(7, 'member', 7) ? 'Allowed' : 'Denied';
Allowed
The policy makes the admin exception and ownership rule visible and testable.
0 of 2 checked
Try this next
0 of 2 completed
Explore 500+ free tutorials across 20+ languages and frameworks.