I am trying to create a php contact form to be sent to my email after being submitted.
NOTES:
-I only want to receive the phone number and message from this contact form to my email; however, I can't get it to do that.
-After the form is submitted, I want to display a thank you message. I get a page not found message instead.
-I want the form to be secure from hacks.
-I also want to validate the phone field to just numbers.
Any help to get this form to work is appreciated.
<?php
// define variables and set to empty values
$nameErr = $emailErr = $phoneErr = "";
$name = $email = $comment = $phone = "";
$to = 'myemail@gmail.com';
$subject = $_POST['Phone'];
$message = $_POST['comment'];
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
if (empty($_POST["phone"])) {
$phoneErr = "Phone is required";
} else {
$phone = test_input($_POST["phone"]);
}
if (empty($_POST["comment"])) {
$comment = "";
} else {
$comment = test_input($_POST["comment"]);
}
//if "email" variable is filled out, send email
if (isset($_POST['Submit'])) {
//send email
mail($to, $subject, $message);
//Email response
echo "Thank you for contacting us!";
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<h2>PHP Form</h2>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<input type="text" name="name" placeholder="Name">
<span class="error">* <?php echo $nameErr;?></span>
<br><br>
<input type="text" name="email" placeholder="E-mail">
<span class="error">* <?php echo $emailErr;?></span>
<br><br>
<input type="text" name="website" placeholder="Phone">
<span class="error"><?php echo $websiteErr;?></span>
<br><br>
<textarea name="comment" placeholder="Concerns?"></textarea>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>