My website allows the users to send an email to the email-address given which is saved in my database. Now that my website is live, I'm testing stuff like this, and it turns out that my contact.php is not working. I always get the message Sorry, there was an error sending your message.
when I try to send an email.
My Contact.php has the following code
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
include 'dbcontroller.php';
if (isset($_POST['sendMessage'])) {
if(empty($_POST['firstname']) || empty($_POST['lastname']) || empty($_POST['email']) || empty($_POST['message'])) {
echo "<script type='text/javascript'>alert('Please fill all the fields.');window.location.href='contact.php'</script>";
}
else{
$sql = "SELECT * from contact";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_array($result);
$to = $row['email'];
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$mailfrom = $_POST['email'];
$message = $_POST['message'];
$headers = "From:" . $firstname . " " . $lastname . "\r\n" . $mailfrom;
if (mail($to, $message, $headers)) {
echo "<script type='text/javascript'>alert('Your email has been sent! Thank you for contacting us!');window.location.href='contact.php'</script>";
}
else{
echo "<script type='text/javascript'>alert('Sorry there was an error sending your message.');window.location.href='contact.php'</script>";
}
}
}
?>
And this is my contact form which is in the same page with the PHP code.
<form method="post" action"">
<label>First Name </label>
<input type="text" class="form-control" placeholder="Firstname" name="firstname" required="required" />
<label>Last Name</label>
<input type="text" class="form-control" placeholder="Lastname" name="lastname" required="required"/>
<label>Email-address</label>
<input type="email" class="form-control" placeholder="Email" name="email" required="required" maxlength="200"/>
<label>Message </label>
<textarea name="message" class="form-control" required="required" rows="4" cols="50" maxlength="500"></textarea>
<input type="submit" name="sendMessage" value="Send Email" class="btn btn-primary pull-right"/>
</form>