As I slowly and steadily build up my library of web dev snippets, I occasionally stop and admire a snippet that I end up coming back much more than I had originally thought I would.
If you wanna quickly review the snippet before we dive in, here it is:
https://gist.github.com/james0r/d9fc2568f4738960dde9ac96053b587b
Alright so what the hell is going on here?
First let’s look at our markup (HTML). Essentially, we have a <form> tag that wraps our <table> that contains rows, <td> and inputs for the values we want (i.e. first name, last name, etc…).
We could easily decouple the markup and the PHP code and have them in separate files— no problem — but for simplicity’s sake, we’ll leave them in the same file. In order to do this we must leave the action="" empty in
Also, we need to add a name="submit" to our submit button input if there isn’t one already:
Our final markup looks like this:
Simple PHP Form Demo
Pretty basic right? Yeah, that’s why this is called a “simple form”!
Okay now to the logic (PHP).
Feel free to customize the PHP to your hearts content, but the only 2 variables you need to configure are:
$email_to = "[email protected]";
$email_subject = "Your email subject line";
You’ll see that even before that, the entire block of PHP is wrapped in an if-statement that checks if anything has been posted by looking for $_POST['email'] in the headers of the http request.
If it evaluates to true (or 1 in this case) it’s like “sweet, let’s process this form and get this data on its way!”.
Next we define a function to print an error message and kill the process if need be:
Next up — a big fat if-statement to ensure that we were passed all of the values we are expecting (tweak to your liking).
// validation expected data exists
if(!isset($_POST['first_name']) ||
!isset($_POST['last_name']) ||
!isset($_POST['email']) ||
!isset($_POST['telephone']) ||
!isset($_POST['comments'])) {
die('We are sorry, but there appears to be a problem with the form you submitted.');
}
Hey wait — we don’t wanna keep typing out $_POST all the damn time do we? No, that’s what I thought. Let’s assign them to our own variables.
$first_name = $_POST['first_name']; // required
$last_name = $_POST['last_name']; // required
$email_from = $_POST['email']; // required
$telephone = $_POST['telephone']; // not required
$comments = $_POST['comments']; // required
This is followed up with a bunch of server-side input validation. You could just as easily remove it and include your own — and/or add client-side validation on top of it — or even do away with validation all together! I don’t recommend it of course, but it’s up to you and your specific use case.
Finally we run our values through clean_string() {} to help prevent PHP injection.
Well that about does it!
Code on and thanks for reading.