Skip to content
Chapter 04 of 05 · 4 lessons · ~40 min

Forms, Email and Sessions

Build a working contact form, validate and sanitize what people type, send email and remember visitors with sessions.

YOUR PROGRESS0%
/ Lessons in this chapter
09
How to Make a Contact Form in PHP How to build a complete, working contact form with PHP, from the HTML to the handler and the thank-you message. Coming soon
10
PHP Form Validation and Sanitizing Input The difference between validating, sanitizing and escaping, and how to apply each one to form data. Coming soon
11
How to Send Email With PHP How to send the contact form to your inbox with mail() or SMTP, and how to keep those emails out of spam. Coming soon
12
PHP Sessions Explained How to remember information about a visitor across pages with sessions, and two practical uses: flash messages and CSRF tokens. Coming soon

Chapter practice task

Task: Build a secure contact form that emails you and shows a thank-you message

  1. Build a form with name, email, service and message fields.
  2. Validate every field on the server and show friendly errors next to each field.
  3. Keep the visitor’s input in the form when there are errors.
  4. Protect the form with a CSRF token stored in a session and a honeypot field.
  5. Send yourself an email with a Reply-To header and redirect to a thank-you message.

By the end of this chapter

  • You can build a complete form handler from scratch
  • You validate on the server and escape every value you print
  • You can send email from PHP and know when to use SMTP instead
  • You can store data across pages with sessions and use them for flash messages and CSRF protection

Quick answers for this chapter

Isn’t HTML5 validation enough?

No. Visitors and bots can skip the browser completely. Browser validation is for convenience; server validation is for safety.

Why do my PHP emails go to spam?

Usually because the server isn’t authorized to send for your domain. Sending through SMTP with SPF, DKIM and DMARC set up fixes most cases.

Where is session data stored?

On the server. The visitor’s browser only keeps a random session ID in a cookie.