Introduction

A contact form is an essential feature for any website, allowing visitors to reach out and establish communication. In this tutorial, we will guide you through the process of setting up a PHP contact form using PHP Mailer with SMTP authentication. PHP Mailer is a popular library that simplifies the task of sending emails via PHP, while SMTP authentication ensures secure and reliable delivery. We will also touch upon styling options and provide references to third-party articles that can assist you in building an effective and visually appealing form.

Step 1: Installing PHP Mailer

This is only required if your host does not have PHP Mailer installed

To begin, you need to install PHP Mailer, which can be easily done using Composer, a dependency management tool for PHP. Open your terminal or command prompt and navigate to your project directory. Then, execute the following command:

Composer will download and install PHP Mailer along with its dependencies.

Step 2: Setting Up the Contact Form

Create a new PHP file for your form, such as contact.php. Note that this is an insecure contact form and isn't the recommended setup for security reasons but provides a basic setup of a contact form:

Remember to replace the SMTP host, your email address, and password with the appropriate values.

Step 3: Styling the Contact Form

Designing an appealing contact form helps create a positive user experience. There are numerous resources available online that offer CSS templates and guides for styling your form. Some popular websites to explore include:

  • CSS-Tricks (https://css-tricks.com/): CSS-Tricks provides tutorials, examples, and articles on various web development topics, including styling forms.

  • CodePen (https://codepen.io/): CodePen is an online community where developers share front-end code snippets, including pre-built form templates that you can modify and use.

  • CSS Frameworks: Frameworks like Bootstrap (https://getbootstrap.com/) and Foundation (https://foundation.zurb.com/) offer ready-to-use form components and styling options.

  • GitHub: Explore GitHub repositories for contact form projects that include both PHP and CSS files, enabling you to learn from existing implementations.

Step 4: Implementing Contact Form Validation and reCAPTCHA

Contact form validation helps ensure that the user inputs valid and complete information before submitting the form. Additionally, integrating reCAPTCHA can further enhance the form's security by preventing spam bot submissions. Follow the steps below to add validation and reCAPTCHA to your contact form:

  • Client-Side Form Validation: Implement client-side form validation using HTML5 attributes and JavaScript. HTML5 provides several built-in form validation attributes such as required, email, and pattern. Utilize these attributes in your HTML form fields to enforce basic validation rules. Additionally, use JavaScript to perform custom validation if necessary.

  • Server-Side Form Validation: Server-side form validation is crucial to ensure data integrity and security. Validate the form inputs on the server-side (in your contact.php file) before sending the email. Verify that the required fields are not empty and that the email address is in the correct format. If any validation fails, display appropriate error messages to the user and prevent the form submission.

  • Integrating reCAPTCHA: To prevent spam bot submissions, integrate reCAPTCHA into your contact form. Follow these steps to implement reCAPTCHA:

    1. Visit the reCAPTCHA website (https://www.google.com/recaptcha) and sign in with your Google account.
    2. Register your website to obtain reCAPTCHA API keys.
    3. In your contact.php file, before the code for sending the email, add the necessary PHP code to validate the reCAPTCHA response. You can find detailed instructions in the reCAPTCHA documentation (https://developers.google.com/recaptcha/docs/verify).
    4. Modify your HTML form to include the reCAPTCHA widget. Place the reCAPTCHA code snippet provided by Google inside your form.
    5. Finally, update your contact.php file to send the email only if the reCAPTCHA response is validated successfully.

Cloudflare Turnstile is an alternative to Google's reCAPTCHA https://www.cloudflare.com/application-services/products/turnstile/

Examples

In the below code examples, the JavaScript code ensures that all required form fields are filled before allowing form submission. If any required field is empty, it prevents the form from being submitted and displays an alert message.

On the server-side (in PHP), the code checks if the required fields are empty using empty(). It also validates the email format using filter_var() with the FILTER_VALIDATE_EMAIL filter. You can add additional custom validation rules as per your requirements.

Remember to adapt and modify the code according to your specific form fields and validation rules.

By combining client-side and server-side form validation, you can enhance the user experience by providing instant feedback and ensure data integrity on the server-side.

Client Side Validation

Server Side Validation

Recommended File and Folder Structure

Setting up a secure PHP contact form requires careful organization of your files and directories. Here's a recommended structure to enhance security and maintainability. Be sure to use the correct folder path for your project. In this example we used public_html but this should match your websites docroot and project structure:

Security Considerations for Your File Structure:

  1. Separate Public and Private Files: Keep sensitive files like configuration and processing logic outside the web root when possible. If you can't place them outside the web root, use .htaccess files to restrict direct access.

  2. Configuration File: Store your SMTP credentials and other sensitive information in a separate configuration file:

  1. Form Handler: Separate the form display from the processing logic:
  1. .htaccess Protection: Add an .htaccess file in your includes directory to prevent direct access:

  2. Sanitize and Validate: Always sanitize inputs and validate form data both client-side and server-side.

  3. Rate Limiting: Implement rate limiting to prevent form spam by using techniques like session-based counters or time-based restrictions.

  4. CSRF Protection: Implement Cross-Site Request Forgery protection by using tokens:

This structure separates your public-facing contact form from the underlying processing logic and sensitive configuration details, making your implementation more secure against common vulnerabilities.

Additional Resources

By implementing contact form validation and integrating reCAPTCHA, Turnstile or another CAPTCHA, you can enhance the security of your contact form and prevent spam bot submissions, ensuring that the messages received are genuine and valuable.

Conclusion

Setting up a contact form with PHP Mailer and SMTP authentication is an effective way to ensure reliable email delivery and enhance communication with your website visitors. By following the steps outlined in this tutorial, you can easily integrate a functional contact form into your website. Note that unauthenticated PHP mail(), PHPMailer, and Sendmail functions are disabled on Lone Star Hosting Shared Plans and SMTP Authentication is required to use any kind of form submission.