Database design: keys, relationships and normalization
Design tables that avoid duplicated data: primary keys, foreign keys, one-to-many and many-to-many relationships.
Create, store and check API keys without keeping a usable secret in the database.
random_bytes().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)
);<?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 onceA fast hash (SHA-256) is fine here because the key is long and random. Passwords are different: use password_hash() for them.
<?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;
}Add a prefix to keys so users can recognise them in a list, and add rate limiting per key.
Design tables that avoid duplicated data: primary keys, foreign keys, one-to-many and many-to-many relationships.
A folder layout and a few habits that keep a growing PHP site tidy, secure and easy to maintain.