📚 Encyclopedia

Web Development · updated 2026-11-16

Slim 4 PHP APIs (and migrating from Limonade)

phpslimapimiddlewarejwtcorsmigration

Justin's PHP APIs (tldr, Hunsley Hills Salon, hampton.website, Forge) share one house shape: Slim 4 as a thin router in public/index.php, plain "manager" classes that hold the logic and talk to MySQL through PDO, JWT or session auth in a middleware, and CORS handled by Apache. The tldr API was migrated from the dead Limonade micro-framework to Slim 4 in March 2026 while moving to PHP 8.3; the manager classes needed almost no changes, only the router was rewritten.

Layout

api/
  public/index.php        # Slim bootstrap + every route (DocumentRoot points HERE)
  public/.htaccess        # front-controller rewrite
  src/Middleware/AuthMiddleware.php
  *_manager.php           # PostManager, UserManager... ($responseCode property, optional $pdo)
  mysql_conf.php          # getPdo(), server-only, gitignored (+ .example committed)
  vendor/

composer require slim/slim:"4.*" slim/psr7 (php-di optional). .htaccess:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ index.php [QSA,L]

Route handler shape

$app->get('/posts/{id}', function (Request $req, Response $res, array $args) use ($pdo) {
    require_once __DIR__ . '/../post_manager.php';
    $pm = new PostManager($pdo);
    $result = $pm->getPost($args['id']);
    $res->getBody()->write(json_encode($result['data'] ?? new stdClass));
    return $res->withHeader('Content-Type', 'application/json')->withStatus($result['code']);
});

Limonade to Slim cheat sheet: dispatch_get('/posts/:id') becomes $app->get('/posts/{id}'); params('id') becomes $args['id']; query params come from $req->getQueryParams(); JSON body from $req->getParsedBody() (needs body-parsing middleware); http_response_code(404) becomes return $res->withStatus(404); $GLOBALS['pdo'] becomes use ($pdo) closure capture. Use require_once for managers to avoid double includes. Slim's error middleware replaces per-route try/catch.

Middleware gotchas

Auth patterns used

CORS

Handled in the Apache vhost, not in PHP, and it works fine behind nginx. List exact origins; an API that only allows the production origin will show CORS errors from localhost during local development, which is expected. The OPTIONS preflight must answer 2xx.

Strict MariaDB and partial updates

MariaDB 10.11 in strict mode rejects NULL for NOT NULL columns. An UPDATE built from client fields breaks when the client omits a field (tldr's editPost got null views/points). Read current values from the DB for fields the client does not send, and give vestigial columns a DEFAULT ''.

tldr API specifics (from the tldr memory)

Hardening a public API (Run API, 2026-10)

The Run game API (Slim 4 + JWT + MySQL, one index.php with ~52 routes) was audited in October 2026 (tldr post #1769). Things that were "fine" (no SQL injection, no IDOR, JWT algorithm pinned, bcrypt, superuser flag re-read from the DB per request, CORS anchored) did not make it safe; these did: - Turn off error details in production: addErrorMiddleware(true, true, true) leaks stack traces. Use addErrorMiddleware(false, ...) with a JSON error handler. The same line sat in the tldr API until November 2026: the first argument is displayErrorDetails, and with it on, even a plain 404 on any unknown path returned the exception type, server file paths and a full stack trace, and an uncaught PDOException would have included its SQL. Tie the flag to an environment variable that only a development machine sets (getenv('TLDR_API_DEBUG') === '1') and keep the other two arguments (logErrors, logErrorDetails) true, so the trace still lands in the php-fpm error log. A production 500 is then debugged from that log, not from the response body. Check every API on a server at once: curl https://api.example.com/nope shows in one request whether traces leak. - Validate client-reported numbers in one shared function used by every submit endpoint (Run's validateRun(): time 0.2-36000 s, medal whitelist, coins 0-100000, ghost blob <= 512 KB, level index range per endpoint). A score endpoint that stores any number the client sends is a leaderboard waiting to be vandalized. - Clamp paging: clampLimit() (1-100) and clampPage() on every list endpoint; an unclamped ?limit= lets one request dump a table. - Cap payloads: a global body limit (4 MB) plus per-endpoint caps (published level JSON <= 1 MB and must parse, feedback <= 5000 chars). - Rate limit in the app if nginx does not: a fixed-window counter table (rate_limits) and rateLimitOk($pdo, bucket, who, max, windowSeconds) that fails open if the DB check errors. Buckets used: auth per IP 30/5 min, auth per user 15/5 min, register per IP 10/h, scores 60/min per user, publish 20/h, feedback 10/h, visit beacon 30/h per IP. - Real client IP behind nginx: read nginx's X-Real-IP (or X-Forwarded-For) in a clientIp() helper; REMOTE_ADDR is always 127.0.0.1 behind the proxy (nginx in front of Apache (TLS proxy on :8008)). - Lock down listing endpoints: an unauthenticated GET /users exposed every account; make admin listings superuser-only. - One helper for repeated checks: the superuser check had been pasted six times and asset CRUD five times; a single isSu($pdo, $userId) keeps behavior consistent. - 401 vs 403 contract: return 401 only for a missing/invalid/expired token and 403 for "authenticated but not allowed". The Run client then clears its session only on a 401 that followed a request which actually carried an Authorization header. - Track composer.lock and commit a schema baseline so the backend can be rebuilt (see Nightly MySQL/MariaDB backups with mysqldump and cron). - Visit-counter pattern: a site_visits table with UNIQUE (session_id, visit_date) and INSERT IGNORE dedupes to one visit per session per day.

Gotchas

See also

Linked from

Sources: tldr memory (completed-work, release-v1.50.0, feature-group-chats, bug-notification-privacy-leak), infra memory (tldr-slim4-migration, server-setup-gotchas), hampton-website memory (api setup), hunsley memory (hhs-deployment), run memory (session-v085.md, session-v086.md, architecture-audit-2026-10.md, improvement-cycles.md, session-v078-v079.md), tldr memory (bug-pass-reset-500), post #1796, tldr memory (fix-api-error-details), post #1896