Reputation: 25
Hi there I have edited some code I have found on-line and everything works besides the validation. It always seems to send an email even when all fields are blank on the contact form that I've created. It is definitely an easy fix but I'm new to this so any help means a great deal to me!!
Thanks.
Heres the code Im using for the php script:
/////////////////////////////////////////////////////
<?php
// Contact subject
$subject ="$Email Enquiry";
// Details
$message=("$cComment") ;
// Mail of sender
$mail_from="$cEmail";
// From
$header="from: $cName <$mail_from>";
// Enter your email address
$to ='[email protected]';
$send_contact=mail($to,$subject,$message, $header);
// Check, if message sent to your email
// display message "We've recived your information"
if($mail_from != "Email"){
header('Location:thanksemail.php');
}
else {
header('Location:emailfail.php');
}
?>
Upvotes: 0
Views: 210
Reputation: 5882
You have put the mail() function outside your if() statement.
Just move it (and complete your if with the other fields):
<?php
if(!empty($mail_from) && !empty($Email)) {
mail($to, $subject, $message, $header);
header('Location:thanksemail.php');
} else {
header('Location:emailfail.php');
}
Upvotes: 0
Reputation: 382
You haven't got any checking code. The code that sends the mail is $send_contact=mail($to,$subject,$message, $header); The checking must be before this code
Try this
if($subject!="" && $cComment!="" && $cEmail!="" && $cName!="" && $mail_from!=""){
$send_contact=mail($to,$subject,$message, $header);
if($mail_from != "Email"){
header('Location:thanksemail.php');
}
else {
header('Location:emailfail.php');
}
}else{
header('Location:emailfail.php');
}
Upvotes: 0
Reputation: 3805
Just as a side note, you can save yourself a line or two of code by verifying if the e-mail was sent like:
if(mail($to,$subject,$message, $header)){
header('Location:thanksemail.php');
}else {
header('Location:emailfail.php');
}
If it comes back true, it was sent. If false, it was not sent.
Upvotes: 0
Reputation: 21553
You need to check if the variables are empty before sending the email. You can do this like so:
if(!empty($variable) and
!empty($variable2)) {
// send the email out here
}
I am using the empty()
function here to detect if the values are empty or not. The following values are considered to be empty values:
"" (an empty string) 0 (0 as an integer) 0.0 (0 as a float) "0" (0 as a string) NULL FALSE array() (an empty array) var $var; (a variable declared, but without a value in a class)
I would also avoid using the standard PHP mail function and instead use a library such as PHPMailer or SwiftMailer to send out your emails instead. They give you more flexibility and both have a much nicer API to work with.
Upvotes: 3