PHP Form Mailer Example [PHP]
As a Web Developer, a common task you may be asked for is to create a contact form. PHP has tools that make it easy to send mail from your server. In this example, I will show you how to easily setup a “form to mail” solution that requires only PHP and no special setup on your server to send mail.
This avoids the requirement for having something like postfix or ssmtp installed on your server, since everything is handled using PHP code. However, if you want to use ssmtp for example, most of the steps remain the same. You would just need to setup your gmail information in the ssmtp config file, and then use the PHP mail() function instead of PHPMailer.
There are two main parts of the solution. One is the HTML form, which is mainly just plain HTML, but with some PHP sections. The second is the PHP code that handles the form submit. In this example we will be submitting to the same page as the form, although the code that handles mailing is in it’s own file.
In the HTML form, there are a few places you will see PHP being used. For each of the fields, we are using the PHP $_POST values, which persists the values entered by the user. This is useful if you need to show validation messages, and preserve the end user’s values.
Also, there is the line with $fm->recaptcha_sitekey
that is used to display the ReCaptcha block. ReCaptcha is recommended as it increases the security of the form. It also prevents many forms of automated spam attacks. I always use ReCaptcha when setting up forms, since it’s relatively easy to set up, and does a great job adding security to the form.
At the top of the HTML form, we have some code that runs $fm->handleSubmit()
. This line is what tells the form to validate the form and send the form data to an email address. In order to do this, the code will need some information. In this example, we are using gmail smtp, so we need those credentials. Also, we need the ReCaptcha site key and secret key. All of these values are provided using the config.php file. Here’s an example config file.
Gmail has some requirements in order to allow sending mail like this. You will need to enable 2 factor authentication. Then you will be able to create a “app password”. More information on how to set this up can be found here.
When you load the form in your browser, that is a GET request, and just loads the form. If you submit the form, this sends a POST request to the form url. When the PHP code sees a POST request, it starts handling the request. The steps involved are:
- Validate user input.
- Validate the ReCaptcha code
- Format and send user data to your email
For step 1, this is not currently shown in the example code. This would involve checking that the user has entered all the desired data, which will show up in the $_POST array in PHP.
For step 2, we check that the user has completed the ReCaptcha test, and submit this information to ReCaptcha API and confirm that the test was successful. That code looks like this:
protected function validateRecaptcha() {
$recaptcha_response = $_POST["g-recaptcha-response"] ?? null;
if (!$recaptcha_response) {
throw new Exception("Please check recaptcha");
}
$recaptcha_verify = json_decode(
file_get_contents(
"https://www.google.com/recaptcha/api/siteverify?secret=" .
$this->recaptcha_secretkey .
"&response=" .
$recaptcha_response
)
);
if ($recaptcha_verify->success !== true) {
throw new Exception("Invalid recaptcha response");
}
}
The last step is to send the mail using PHPMailer, which looks like this:
protected function sendEmail() {
$to = $this->gmail_user;
$from = $this->gmail_user;
$mail = new PHPMailer(true);
$mail->isSMTP();
$mail->Host = "smtp.gmail.com";
$mail->SMTPAuth = true;
$mail->Port = 587;
$mail->Username = $this->gmail_user;
$mail->Password = $this->gmail_password;
$mail->Subject = "Contact Form";
$mail->addAddress($to);
$mail->setFrom($from);
$mail->isHTML(true);
$mail->Body = $this->getEmailBody();
$mail->AltBody = $this->getEmailAltBody();
$mail->send();
}
The complete example can be found on github. I hope this helps you set up your own contact form using PHP.