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 require phpmailer/phpmailer

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, and include the following code:

<?php
require 'vendor/autoload.php'; // Include PHP Mailer

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Retrieve form data
    $name = $_POST['name'];
    $email = $_POST['email'];
    $message = $_POST['message'];

    // Create a new PHP Mailer instance
    $mail = new PHPMailer(true);

    try {
        // Configure SMTP settings
        $mail->isSMTP();
        $mail->Host = 'smtp.example.com';
        $mail->SMTPAuth = true;
        $mail->Username = '[email protected]';
        $mail->Password = 'your_password';
        $mail->SMTPSecure = 'tls';
        $mail->Port = 587;

        // Set email content and recipients
        $mail->setFrom($email, $name);
        $mail->addAddress('[email protected]');
        $mail->Subject = 'New Contact Form Submission';
        $mail->Body = $message;

        // Send the email
        $mail->send();
        echo 'Message sent successfully!';
    } catch (Exception $e) {
        echo 'Message could not be sent. Error: ', $mail->ErrorInfo;
    }
}
?>

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. There are many online resources and tutorials available that cover HTML5 form validation and JavaScript validation techniques.
  • 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:a. Visit the reCAPTCHA website (https://www.google.com/recaptcha) and sign in with your Google account.b. Register your website to obtain reCAPTCHA API keys.c. 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).d. Modify your HTML form to include the reCAPTCHA widget. Place the reCAPTCHA code snippet provided by Google inside your form.e. Finally, update your contact.php file to send the email only if the reCAPTCHA response is validated successfully.

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:

<form id="contact-form" action="contact.php" method="POST"> 
  <input type="text" id="name" name="name" required placeholder="Your Name"> 
  <input type="email" id="email" name="email" required placeholder="Your Email"> 
  <textarea id="message" name="message" required placeholder="Your Message"></textarea> 
  <button type="submit">Submit</button> 
</form> 
 
<script> 
  document.getElementById("contact-form").addEventListener("submit", function(event) { 
    var nameInput = document.getElementById("name"); 
    var emailInput = document.getElementById("email"); 
    var messageInput = document.getElementById("message"); 
 
    if (nameInput.value === "" || emailInput.value === "" || messageInput.value === "") { 
      event.preventDefault(); // Prevent form submission 
      alert("Please fill in all required fields."); 
    } 
  }); 
</script> 
Server-Side Form Validation (PHP): 
php 
Copy code 
<?php 
// Other code... 
 
// Server-side validation 
if ($_SERVER["REQUEST_METHOD"] == "POST") { 
    $name = $_POST['name']; 
    $email = $_POST['email']; 
    $message = $_POST['message']; 
 
    // Validate required fields 
    if (empty($name) || empty($email) || empty($message)) { 
        echo "Please fill in all required fields."; 
        exit; 
    } 
 
    // Validate email format 
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { 
        echo "Invalid email format."; 
        exit; 
    } 
 
    // Additional custom validation rules if needed 
 
    // Process the form submission 
    // ... 
} 
?> 

Server Side Validation:

<?php
// Other code...

// Server-side validation
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $name = $_POST['name'];
    $email = $_POST['email'];
    $message = $_POST['message'];

    // Validate required fields
    if (empty($name) || empty($email) || empty($message)) {
        echo "Please fill in all required fields.";
        exit;
    }

    // Validate email format
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        echo "Invalid email format.";
        exit;
    }

    // Additional custom validation rules if needed

    // Process the form submission
    // ...
}
?>

Additional Resources:

By implementing contact form validation and integrating reCAPTCHA, 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.


0 Comments

Leave a Reply

Avatar placeholder

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.