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
- Slim 4 middleware is LIFO. The last one added is the outermost and runs first on the
request. A middleware that needs the parsed body cannot rely on
getParsedBody()if the body parser was added before it (it runs inside, later). Read the raw body yourself:$raw = (string) $req->getBody(); ...; $req->getBody()->rewind(); $_POSTis empty for JSON requests. PHP only fills it for form-encoded and multipart bodies. Legacy managers that read$_POSTbreak when a Flutter or JS client sends JSON. A shim middleware decodes the JSON body into$_POST, then rewinds the stream. Aparams()shim filling$GLOBALS['_slim_route_args']likewise kept old managers working.php://inputis re-readable on PHP 8.3 + php-fpm (verified empirically), so managers that read it directly still work after Slim has read the body. Not guaranteed on every SAPI.- PSR-4 is case sensitive. Namespace
App\Middlewaremust live insrc/Middleware/; a lowercasesrc/middleware/gives "does not comply with psr-4" and class-not-found on Linux. write(null)throws a TypeError under PHP 8 strict typing. Managers thatreturn;on success return null, so every handler usedwrite($result ?? '').
Auth patterns used
- Group protected routes:
$app->group('', function ($g) {...})->add(new AuthMiddleware());, public routes (register, login, health check) outside the group. The middleware sets attributes likeauthorized_username/authorized_roleon the request. - JWT HS256 with a secret in a server-only config file and a 30-day expiry. Some clients send
the raw token in
Authorizationwith noBearerprefix; the middleware must match whatever the client sends. Decide once and document it. firebase/php-jwtwas blocked once by a Composer security advisory; a self-contained HS256 implementation (base64url +hash_hmac('sha256')+hash_equals) is ~30 lines and avoids the dependency.- Hash passwords with
password_hash()/password_verify()(bcrypt), not hand-rolled sha256 + salt. - Derive identity from the verified token, never from a username in the body.
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)
- Health check semantics: on the tldr API,
GET /returns 200 with the bodysup g?when PHP, Slim and the DB connection are all fine. 418 on every route means the PDO bootstrap failed (DB down or a brokenmysql_conf.php). 500 means PHP itself broke. The smoke test decodes these, see Writing a production smoke test that tells you why it failed. - Closure
uselists.$pdois created once at the top ofindex.php; every route closure must capture it withuse ($pdo, $managerDir). The login route only haduse ($managerDir); when a change made it construct a manager with$pdo, it got null and fataled with "Call to a member function prepare() on null". The Flutter client then showed "Incorrect username or password", because it could not parse Slim's HTML 500 page as JSON. Lesson: a parse failure on the client should surface as a server error, not as a credential error. - Reuse the injected
$pdoin managers. Managers that opened their own connections madeGET /posts/{id}open three. HavegetPdo()return the injected handle when set. - File uploads need POST. PHP only populates
$_FILESfor POST multipart requests, so an "update avatar" route isPOST /users/{u}/avatar, not PUT. Validate the real type server-side withfinfo, not the client's extension or MIME. - CORS
Allow-Methodsis a contract. The tldr API vhost allows GET, POST, PUT, DELETE only; a PATCH route fails preflight from the browser. Rename routes became PUT for that reason. - Named placeholders used twice in one query (
:u ... :u) only work with PDO emulated prepares (the default). Turning emulation off breaks those queries. POST /postsanswers 201 with an empty body; clients have to find the new post another way. Return the new id from create endpoints.- CRLF files:
api/util.phphas CRLF line endings. Scripted rewrites (Python) normalize to LF; restore withsed -i 's/$/\r/'to keep diffs clean. - Local testing against real services: a gitignored stub of the server-only AI config pointing
at
http://127.0.0.1:9100letsphp -rexercise the AI manager against the real local service. For PHP/Dart mirrored logic (e.g. auto-title derivation), extract the PHP function on the server and eval it against the same test cases as the Dart unit tests.
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
- A bare
require 'util.php'can take down one endpoint for months. TLDR's forgot-password request returned an empty-body 500 for every user for about two months: a later commit addedrequire_once __DIR__ . '/util.php'to a manager's constructor, and the reset method still did a plainrequire 'util.php', which loaded the file a second time and hit the fatal "Cannot redeclare hi()" (util.php declares functions withoutfunction_existsguards). Fatals bypass Slim's error middleware, so the client sees only a bare 500; the cause is in the Apache/php-fpm error log. Rule: alwaysrequire_once __DIR__ . '/file.php'(the__DIR__also stops include-path surprises), and grep for barerequire/includewhen adding a new include anywhere. Rarely used flows (password reset) need an end-to-end test after any change to shared includes. - Bots fill the error log. With error logging on, every 404/405 from a scanner probing for paths that do not exist writes a full stack trace. On a server with several Slim APIs sharing one php-fpm pool the log grew by 15 to 115 MB a week, almost all of it probes. Make sure the log is rotated, and expect to grep past the noise when looking for a real error.
- Other small leaks worth knowing about:
X-Powered-By: PHP/8.xis sent unless php.ini setsexpose_php = Off, and a "database is down" response that echoes the PDO connect message can name the database user. - DELETE requests in tldr read their arguments from query params, not the body.
- No local PHP or Composer on the desktop at times: lint with
ssh server "php -l" < public/index.php; run composer on the server or use a checksum-verifiedcomposer.pharintools/.
See also
- PHP 7 to 8 upgrade breakage and other PHP traps
- TLDR platform architecture (tldrnerd.com)
- Apache vhost gotchas (icons alias, manifests, SPA fallback, redirects)
- API authorization from the verified identity (and the holes it closes)
Linked from
- API authorization from the verified identity (and the holes it closes)
- Client/server sync pitfalls (deletes, timestamps, merge policies)
- GIF search behind a server proxy (Tenor shutdown, GIPHY, MMS size budgets)
- Nightly MySQL/MariaDB backups with mysqldump and cron
- PHP 7 to 8 upgrade breakage and other PHP traps
- Setting up an Alma Linux 9 LAMP server
- Speedrun timers, medals, leaderboards, and anti-cheat
- The missing index behind a slow list endpoint
- TLDR platform architecture (tldrnerd.com)