18
1
0
How to create a Simple Contact Form with PHP (No Framework Needed)

How to create a Simple Contact Form with PHP (No Framework Needed)

Published on July 3, 2025 by OBSCountdown Editorial

Simple Contact Form with PHP (No Framework Needed)

Learn how to build a secure and working contact form using just PHP and HTML , no frameworks required.

๐Ÿ“ฌ Why Build a Contact Form?

A contact form allows users to reach out to you directly from your website. With PHP, you can process the form data, validate it, and send it via email in just a few lines of code.

๐Ÿ“„ Step 1: Create the HTML Form

<form method="post" action="">
  <label>Name:</label><br>
  <input type="text" name="name" required><br>

  <label>Email:</label><br>
  <input type="email" name="email" required><br>

  <label>Message:</label><br>
  <textarea name="message" required></textarea><br>

  <button type="submit">Send</button>
</form>

โš™๏ธ Step 2: Handle Form Submission in PHP

Add this PHP code at the top of the same file to process the submission:

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
  $name = strip_tags(trim($_POST["name"]));
  $email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
  $message = htmlspecialchars(trim($_POST["message"]));

  if (filter_var($email, FILTER_VALIDATE_EMAIL) && !empty($name) && !empty($message)) {
    $to = "[email protected]"; // Replace with your email
    $subject = "New Contact Message from $name";
    $body = "Name: $name\nEmail: $email\nMessage:\n$message";
    $headers = "From: $name <$email>";

    if (mail($to, $subject, $body, $headers)) {
      echo "<p>Message sent successfully!</p>";
    } else {
      echo "<p>Message failed to send.</p>";
    }
  } else {
    echo "<p>Please fill all fields correctly.</p>";
  }
}
?>

โš ๏ธ Important: The built-in mail() function may not work reliably in shared hosting or cloud servers due to strict email authentication policies. It's strongly recommended to use SMTP for sending emails securely.

๐Ÿ“ก Step 3: Use SMTP for Secure Email Sending

Using SMTP helps ensure that your emails are authenticated and less likely to be marked as spam. You can use libraries like PHPMailer or SwiftMailer.

Hereโ€™s a basic example with PHPMailer:

// Install with Composer: composer require phpmailer/phpmailer
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'vendor/autoload.php';

$mail = new PHPMailer(true);
try {
  $mail->isSMTP();
  $mail->Host = 'smtp.yourdomain.com';
  $mail->SMTPAuth = true;
  $mail->Username = '[email protected]';
  $mail->Password = 'yourpassword';
  $mail->SMTPSecure = 'tls';
  $mail->Port = 587;

  $mail->setFrom('[email protected]', 'Your Name');
  $mail->addAddress('[email protected]');
  $mail->Subject = 'New Contact Form Message';
  $mail->Body    = "Name: $name\nEmail: $email\n$message";

  $mail->send();
  echo 'Message has been sent';
} catch (Exception $e) {
  echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}

๐Ÿ” Email Authentication: SPF, DKIM, and DMARC

To ensure that your domainโ€™s emails are not rejected or marked as spam, set up proper DNS records:

  • SPF (Sender Policy Framework): Specifies allowed sending servers.
  • DKIM (DomainKeys Identified Mail): Adds a digital signature to verify authenticity.
  • DMARC (Domain-based Message Authentication, Reporting & Conformance): Tells email providers how to handle failures in SPF/DKIM checks.

Use tools like MXToolbox to test your configuration.

๐Ÿ”’ Basic Security Tips

  • Always sanitize and validate inputs
  • Limit the form to known fields only
  • Use CAPTCHA or reCAPTCHA to block bots
  • Log IP addresses and rate limit requests

โœจ Optional Enhancements

  • Send a confirmation email to the user
  • Store messages in a database
  • Use AJAX submission for a smoother UX
  • Use CSRF tokens for added protection
Comments (0)

No comments yet. Be the first to comment!

Leave a Comment
Replying to someone's comment. Cancel
18
1
0
Join Our OBS Community

Loading...

Join Now