My PHP contact form is working properly and sending info to my email when a user enters valid data into fields and hits submit, but it is also sending me a blank email every time I load the page containing the form. I'm thinking it may have something to do with my submission conditionals:
Submit button code:
<div class="col-md-12 submit-button">
<input type="submit" class="btn btn-success btn-send" value="Send message" />
<div class="success"><?= $success ?></div>
</div>
Form_process.php send code:
if ($name_error == '' and $email_error == '' and $phone_error == '' ){
$message_body = '';
unset($_POST['submit']);
foreach ($_POST as $key => $value) {
$message_body .= "$key: $value\n";
}
$to = '[email protected]';
$subject = 'contact form submitted';
if(mail($to, $subject, $message_body)){
$success = "Thank you for contacting us, we will get back to you as soon as possible.";
$name = $email = $organization = $phone = $message = '';
}
}
Thanks!
You have to check if the form is submitted before execute the send email script.
First add a name to your submit input
<div class="col-md-12 submit-button">
<input name="submit" type="submit" class="btn btn-success btn-send" value="Send message" />
<div class="success"><?= $success ?></div>
</div>
Then wrap your send email code inside a if, check whether the $_POST['submit'] is presented
if (isset($_POST['submit'])) {
// your send email code
}