Secure PHP Contact Form Handler
A more real-world contact form endpoint for bespoke PHP builds. Includes request method enforcement, CSRF validation, anti-bot checks, sane input validation, response helpers and a clean place to wire PHPMailer or your preferred provider.
Stack / dependencies
Compatibility
Usage notes
Use this as your form action endpoint, for example /contact-submit.php. It supports both regular form posting and an AJAX flow because responses are returned in a predictable format.
- Generate a CSRF token on the form page and store it in
$_SESSION['contact_csrf']. - Include a hidden
websitefield as a honeypot. - Post
name,email,messageand optionalphone. - Swap the delivery block for PHPMailer, SMTP or API-based mail once ready.
Why this exists
Most “contact form snippets” are too toy-like for a live project. This version is designed to be small enough to understand, but structured enough to sit behind a real business site.
Integration steps
- 1 Add a CSRF token to the form page and include it as a hidden input.
- 2 Add a visually hidden honeypot input named website.
- 3 Point your form action to this file or call it via fetch().
- 4 Replace the example delivery section with PHPMailer or your mail provider.
- 5 Log failures server-side rather than exposing internal mail errors to users.
Code snippet
Full version with formatting intact. Use “Copy stripped version” when you want a leaner base.
Implementation notes
Security notes
- CSRF protection stops cross-site submission attempts from other origins.
- The honeypot blocks a chunk of low-grade bot traffic without adding user friction.
- Inputs are trimmed and validated before any delivery logic runs.
- Real mail failures should be logged server-side, not returned raw to the browser.
Performance notes
Keep the handler light and avoid expensive external API calls in the request path unless needed. If you later add CRM sync, consider queueing or logging locally first.
FAQ
Tags
Related snippets
View allPDO Bootstrap (db.php pattern)
A stronger db bootstrap for bespoke PHP apps. Uses static reuse, utf8mb4, disabled emulated prepares, clear exception handling and small helper structure that fits shared hosting as well as more advanced setups.
PHP Login Rate Limiter (Session Based)
A slightly more production-shaped login limiter that blocks repeated attempts over a lock window, returns consistent responses and gives you a cleaner place to evolve later into database or IP-backed rate limiting.
SEO + Open Graph Block for PHP Layouts
A more complete meta head block for bespoke PHP layouts. Supports title, description, canonical, robots, OG and Twitter cards, while keeping page overrides easy via a simple $seo array.