PHP Cookbook
“How would you do X?” — practical, production-ready recipes with the approach, full code, pitfalls and variations.
PHP
- Add CSRF protection to PHP formsPrevent cross-site request forgery on session-authenticated forms without a framework.
- Add health check endpoints to a PHP appLet load balancers and Kubernetes know whether a PHP instance is alive and ready for traffic.
- Add structured logging with request IDs in PHPMake PHP logs searchable and correlate all log lines from one request.
- Build a secure password reset flow in PHPLet users reset forgotten passwords without enabling account takeover or email enumeration.
- Cache expensive queries with Redis in PHPSpeed up a slow product listing query with Redis while keeping data reasonably fresh.
- Call external APIs with timeouts and retries in PHPCall a flaky third-party API without hanging PHP-FPM workers or amplifying outages.
- Handle file uploads securely in PHPAccept user image uploads safely: validate type and size, avoid executable files, and store them outside the web root.
- Implement rate limiting in a PHP APILimit each client to N requests per minute across multiple PHP-FPM servers and return 429 with Retry-After.
- Make a PHP payment endpoint idempotentPrevent double charges when clients retry a POST /payments request after a timeout.
- Paginate large tables with cursors in PHPList orders efficiently in an API without slow OFFSET queries on large tables.
- Prevent XSS in PHP templatesRender user-generated content (names, comments, links) safely in HTML pages.
- Protect a PHP API with JWT bearer tokensValidate JWT access tokens on every API request and expose the authenticated user to controllers.
- Receive and verify webhooks in PHPProcess payment provider webhooks safely: verify signatures, avoid duplicates and respond quickly.
- Retry deadlocked transactions in PHPHandle deadlocks and serialization failures gracefully in high-concurrency write paths.
- Run scheduled jobs (cron) reliably in PHPRun nightly reports and cleanups without overlapping runs or silent failures.
- Send emails asynchronously with a queue in PHPSend welcome and receipt emails without slowing down requests or losing them when the mail provider is down.
- Set up a PHP dev environment with Docker ComposeGive every developer the same PHP, database and Redis versions with one command.
- Test database code in PHP with transactionsWrite fast, isolated PHPUnit tests for repository code against a real database.
- Validate JSON API input in PHPValidate and normalize a JSON request body, returning all errors in a consistent 422 response.
- Wire a PHP app with a DI containerStop creating dependencies with `new` all over the code and make classes testable.