I have a problem with php function mail(). It doesn't send any emails :(. I'm totally new to php and created the code by using a lot of tutorials, so I think it might just be wrong.
Also I'm having problem with validation below the button code. I want to validate if the user entered the valid email and if not, echo nothing, because it will show red error anyway.
Right now when email is invalid it shows "Email sent" message But first of all I want to email actually send.
Also hosting is blocking the SSL protocol if there's no header "From::". Is it placed correctly?
<h4>Contact form</h4>
<?php
$NameErr = $EmailErr = $SubErr = $MessErr = "";
$Name = $Email = $Subject = $Message = "";
$To = "blackmagic@xxx.com";
$headers = "From: blackmagic@xxx.com Name: $Name\n $Message\n E-Mail: $Email\n";
$n = NULL;
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["Name"])) {
$NameErr = "Name is required";
} else {
$Name = test_input($_POST["Name"]);
}
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"]);
if (!filter_var($Email, FILTER_VALIDATE_EMAIL)) {
$EmailErr = "Invalid email format";
}
}
if (empty($_POST["Subject"])) {
$SubErr = "Subject is required";
} else {
$Message = test_input($_POST["Subject"]);
}
if (empty($_POST["Message"])) {
$MessErr = "Message is required";
} else {
$Message = test_input($_POST["Message"]);
}
}
$Name = test_input($_POST["Name"]);
$Email = test_input($_POST["Email"]);
$Subject = test_input($_POST["Subject"]);
$Message = test_input($_POST["Message"]);
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<p><input class="w3-input w3-padding-16" type="text" placeholder="Name" name="Name"></p>
<span class="error"><?php echo $NameErr; ?></span>
<p><input class="w3-input w3-padding-16" type="text" placeholder="Email" name="Email"></p>
<span class="error"><?php echo $EmailErr; ?></span>
<p><input class="w3-input w3-padding-16" type="text" placeholder="Subject" name="Subject"></p>
<span class="error"><?php echo $SubErr; ?></span>
<p><input class="w3-input w3-padding-16" type="text" placeholder="Message" name="Message"></p>
<span class="error"><?php echo $MessErr; ?></span>
<p>
<button class="w3-btn w3-grey w3-padding-large w3-hover-green" type="submit" value="1" name="pressed">
<i class="fa fa-paper-plane"></i> SEND MESSAGE
</button>
</p>
</form>
<?php
if (isset($_POST["pressed"])) {
mail($To, $Subject, $Message, $headers);
if (empty($_POST["Name" or "Email" or "Subject" or "Message"])) {
echo $n;
}
if (isset($Name) and ( $Email) and ( $Subject) and ( $Message)) {
echo "Email sent.";
}
}
?>
</div>