Secure REST APIs in PHP without a framework
A small educational PHP JSON API with PDO, opaque tokens and per-resource authorization.
A small educational PHP JSON API with PDO, opaque tokens and per-resource authorization.
Scope
Use a single public front controller for GET, POST, PATCH and DELETE on /api/items and /api/items/{id}. Return JSON consistently and 405 with Allow for unsupported methods. Do not expose other PHP files through the web server.
Authentication
Generate opaque tokens with random_bytes(32), display each once and store only its SHA-256 hash with user, expiry and revocation state. Accept Authorization: Bearer over HTTPS, look up the hash with a parameterized query and return 401 for missing or invalid credentials. Rate-limit attempts and never log tokens.
Authorization and input
Every item query must include the authenticated user ID, such as WHERE id = :id AND user_id = :uid. Validate types and lengths, explicitly list writable fields and use PDO prepared statements with exception handling. Distinguish malformed JSON (400), invalid input (422), forbidden operations (403) and missing objects (404), without exposing internal errors.
Deployment
Keep secrets outside the public directory, grant the SQL account minimal rights, limit request size, enforce HTTPS and protect logs. CORS controls browsers but is not authorization. Test cross-account access, expired tokens and malformed payloads before publishing.
References
https://www.php.net/manual/en/book.pdo.php ; https://www.php.net/manual/en/function.random-bytes.php ; https://cheatsheetseries.owasp.org/cheatsheets/REST_Security_Cheat_Sheet.html
Share
What's Your Reaction?
Like
0
Dislike
0
Love
0
Funny
0
Angry
0
Sad
0
Wow
0