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