API keys and tokens done safely in PHP

Advanced  Nov 3, 2026

Create, store and check API keys without keeping a usable secret in the database.

API keys and tokens done safely in PHP
The steps of this tutorial at a glance.
The steps of this tutorial at a glance.

Principles

  • Generate keys with random_bytes().
  • Show the full key once, then store only a hash.
  • Allow revoking and expiry.
  • Send keys in a header, over HTTPS, never in the URL.
The main points of this section.
The main points of this section.

Table

CREATE TABLE api_keys (
  id INT AUTO_INCREMENT PRIMARY KEY,
  user_id INT NOT NULL,
  key_prefix CHAR(8) NOT NULL,
  key_hash CHAR(64) NOT NULL,
  revoked TINYINT(1) NOT NULL DEFAULT 0,
  last_used DATETIME NULL,
  UNIQUE KEY (key_hash)
);
The table described by the SQL above.
The table described by the SQL above.
How the code in this section fits into the page.
How the code in this section fits into the page.

Create

<?php
$key = 'kb_' . bin2hex(random_bytes(24));
$pdo->prepare('INSERT INTO api_keys (user_id, key_prefix, key_hash) VALUES (?, ?, ?)')
    ->execute([$userId, substr($key, 0, 8), hash('sha256', $key)]);
echo $key;   // show once

A fast hash (SHA-256) is fine here because the key is long and random. Passwords are different: use password_hash() for them.

How the code in this section fits into the page.
How the code in this section fits into the page.

Check

<?php
$header = $_SERVER['HTTP_AUTHORIZATION'] ?? '';
if (!preg_match('/^Bearer\s+(\S+)$/', $header, $m)) {
    http_response_code(401);
    exit;
}

$s = $pdo->prepare('SELECT user_id FROM api_keys WHERE key_hash = ? AND revoked = 0');
$s->execute([hash('sha256', $m[1])]);
$user = $s->fetchColumn();
if ($user === false) {
    http_response_code(401);
    exit;
}

Also

Add a prefix to keys so users can recognise them in a list, and add rate limiting per key.

More tutorials