SoftwareWebsite

Simple php based conact form

Here’s a simple PHP contact form that you can use:

<form action="contact.php" method="post">
<label for="name">Name:</label><br>
<input type="text" id="name" name="name"><br>
<label for="email">Email:</label><br>
<input type="email" id="email" name="email"><br>
<label for="message">Message:</label><br>
<textarea id="message" name="message"></textarea><br>
<input type="submit" value="Submit">
</form>

This form has three fields: name, email, and message. When the user submits the form, the data is sent to the “contact.php” file.

To process the form data, you can create a PHP script called “contact.php” with the following code:

<?php

if ($_SERVER["REQUEST_METHOD"] == "POST") {

$name = trim(filter_input(INPUT_POST,"name",FILTER_SANITIZE_STRING));

$email = trim(filter_input(INPUT_POST,"email",FILTER_SANITIZE_EMAIL));

$message = trim(filter_input(INPUT_POST,"message",FILTER_SANITIZE_SPECIAL_CHARS));if ($name == "" || $email == "" || $message == "") {

echo "Please fill in the required fields: Name, Email, and Message";

exit;

}

$email_body = "";
$email_body .= "Name: " . $name . "\n";
$email_body .= "Email: " . $email . "\n";
$email_body .= "Message: " . $message . "\n";

// To send an email, you'll need to use the PHP mail() function.
// Replace the following line with your own email address and subject line.
$to = "[email protected]";
$subject = "New Contact Form Submission";
$headers = "From: $email";
if (mail($to, $subject, $email_body, $headers)) {
echo "Thank you for your email! We'll get back to you as soon as possible.";
} else {
echo "There was a problem sending your email. Please try again.";
}
}
?>

This PHP script first checks if the form has been submitted using the POST method. If it has, it sanitizes the form data to prevent against cross-site scripting (XSS) attacks, and then checks if any of the required fields (name, email, and message) are empty. If any of the fields are empty, it displays an error message.

If all the required fields are filled out, the script creates an email body by concatenating the form data, and then uses the PHP mail() function to send an email with the form data to a specified email address. If the email is sent successfully, it displays a thank-you message. If there is a problem sending the email, it displays an error message.

I hope this helps! Let me know if you have any questions.

Tags

Related Articles

Leave a Reply

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

Back to top button
Close
Close