Content · Web Development · PHP

Building a PHP API with Token Authentication

Require a bearer token and compare only its server-side digest with a stored record. Use HTTPS, scoped tokens, explicit expiry and constant-time comparison; do not log Authorization

1 views Published Oct 17, 2026 Updated Oct 17, 2026 admin

Require a bearer token and compare only its server-side digest with a stored record.

The objective is to understand the behavior and operational limits, not only the method name.

What It Does


Require a bearer token and compare only its server-side digest with a stored record.

Prerequisites


Use a dedicated development environment and sample data. Where a snippet uses an injected connection, repository, request value or mailer, supply it from your own application setup.

Example 1: Basic Use


A focused working pattern for this topic. Names such as $pdo, $authContext and $repo represent dependencies provided by the application unless initialized in the snippet.

<?php
$header = $_SERVER['HTTP_AUTHORIZATION'] ?? '';
if (!preg_match('/^Bearer ([A-Za-z0-9_-]{32,})$/', $header, $m)) { http_response_code(401); exit; }
$digest = hash('sha256', $m[1]);
$stmt = $pdo->prepare('SELECT user_id FROM api_tokens WHERE token_hash = ? AND expires_at > CURRENT_TIMESTAMP');
$stmt->execute([$digest]);
$userId = $stmt->fetchColumn();
if ($userId === false) { http_response_code(401); exit; }

Example 2: A Second Scenario


A second use case that adds a different operation or data flow specific to this topic.

<?php
$token = bin2hex(random_bytes(32));
$digest = hash('sha256',$token);
$stmt = $pdo->prepare('INSERT INTO api_tokens (user_id,token_hash,expires_at) VALUES (?,?,?)');
$stmt->execute([$userId,$digest,gmdate('Y-m-d H:i:s',time()+3600)]);

Example 3: Practical Checks


A practical validation, failure or deployment concern specific to this topic.

<?php
$authorization = $_SERVER['HTTP_AUTHORIZATION'] ?? '';
if (!preg_match('/^Bearer ([A-Za-z0-9_-]{32,})$/', $authorization, $match)) { http_response_code(401); exit; }
$digest = hash('sha256',$match[1]);
$stmt = $pdo->prepare('SELECT user_id FROM api_tokens WHERE token_hash = ? AND revoked_at IS NULL');
$stmt->execute([$digest]);

Important Behavior and Edge Cases


Use HTTPS, scoped tokens, explicit expiry and constant-time comparison; do not log Authorization headers.

For production use, also account for error handling, data validation, resource limits and environment-specific driver behavior.

Comparison with Related Approaches


ApproachImportant distinction
Building a PHP API with Token AuthenticationRequire a bearer token and compare only its server-side digest with a stored record.
Related API / patternUse this workflow as a focused starting point rather than a substitute for application-level tests.

Common Beginner Mistakes


MistakeCorrect approach
Assuming the happy path covers edge casesUse HTTPS, scoped tokens, explicit expiry and constant-time comparison; do not log Authorization headers.
Using a related API interchangeablyUse this workflow as a focused starting point rather than a substitute for application-level tests.

Key Takeaways


  • Require a bearer token and compare only its server-side digest with a stored record.
  • Use HTTPS, scoped tokens, explicit expiry and constant-time comparison; do not log Authorization headers.
  • Use this workflow as a focused starting point rather than a substitute for application-level tests.

Choose this API or pattern when its exact semantics match your task, and verify the result against the database driver and runtime used by your application.

Share this resourceSend this page to someone who may find it useful.