Quick TipWritten on

Render a static HTML file from PHP

You want to create this static website with instant loading times, green performance fireworks in Lighthouse and wonderful, hand-thrown HTML. There is this perfect first client: A little hairdressing studio. They just want a simple four-page site (set and forget).

But -- there is always a but -- when the site is nearly finished, they decided that the contact form no longer sends emails to an account. Instead, it should just put that data into that new CRM their cousin wrote. We should call or send to a Jason and give him a REST or whatever.

No dynamic backend in Jamstack land

Well, we don't have a backend -- that's for sure. But luckily we are hosting on the client's classic web space hosting service. It has all the classic Apache and PHP bells and whistles. We could scratch the project, start over with WordPress, let the client's budget explode (which is already about trending to zero) by adjusting everything and get on with life.

Or we just make a dynamic /contact/ page. The new file structure looks like this:

├─ public/
│  └─ contact/
│     ├─ .htaccess
│     ├─ index.php
│     ├─ contact.html
│     └─ thanks.html

The .htaccess is pretty easy: It rewrites / of that folder to the index.php file and ignores everything else. The contact.html and thanks.html shouldn't be accessible directly any longer.

Then we write our little PHP script. When visitors come to the page it starts a session, it reads the contact.html file and renders it to the response. The form on that page sends a post request to the same URL on submit, so we can evaluate the submitted data in the same PHP file.


  if (!empty( $_POST )) {
      // Handle the business side of the request here ...

      // Validate the form input, check the previous XSS token, build the
      // response JSON object and send it to the REST API. In case we have an
      // error -- well then we skip through the thanks page and return the
      // contact page again. Otherwise invalidate the session, render the thanks
      // page and end the request.

      // Render the thanks page
  // Start the session (if needed and it's not yet running)
  // You might also want to generate and set a token for XSS protection. For
  // that you'd have to read the file into a variable, replace a placeholder
  // with it and render it to the response.

  // Render the form or stuff

That's it. It doesn't block the generation of your files, you can test them in your development environment and you just added two more files. Hope it helps someone. Have a nice day.