I fill the next form:
<form name="frmContacto" class="form-horizontal" method="GET" action="./mail/contact_me.php">
<fieldset>
<legend class="text-center header">Formulario de contacto</legend>
<div class="form-group">
<span class="col-md-1 col-md-offset-2 text-center"><i
class="fa fa-user bigicon"></i></span>
<div class="col-md-8">
<input id="name" name="name" type="text" placeholder="Nombre"
class="form-control">
</div>
</div>
<div class="form-group">
<span class="col-md-1 col-md-offset-2 text-center"><i
class="fa fa-envelope-o bigicon"></i></span>
<div class="col-md-8">
<input id="email" name="email" type="text" placeholder="Correo electrónico"
class="form-control">
</div>
</div>
<div class="form-group">
<span class="col-md-1 col-md-offset-2 text-center"><i
class="fa fa-phone-square bigicon"></i></span>
<div class="col-md-8">
<input id="phone" name="phone" type="text" placeholder="Teléfono"
class="form-control">
</div>
</div>
<div class="form-group">
<span class="col-md-1 col-md-offset-2 text-center"><i
class="fa fa-pencil-square-o bigicon"></i></span>
<div class="col-md-8">
<textarea class="form-control" id="message" name="message"
placeholder="Introduce aquí tu mensaje." rows="7"></textarea>
</div>
</div>
<div class="form-group">
<div class="col-md-12 text-center">
<a href="mailto:xxx#gmail.com?Subject=Hello%20again" target="_top">
<button type="submit" class="btn btn-primary btn-lg">Enviar</button>
</a>
</div>
</div>
</fieldset>
</form>
PHP side:
<?php
$name = isset($_GET['name']);
echo $name;
$email_address = isset($_GET['email']);
echo $email_address;
$phone = isset($_GET['phone']);
echo $phone;
$message = isset($_GET['message']);
echo $message;
// Create the email and send the message
$to = 'xxx#gmail.com'; // Add your email address inbetween the '' replacing yourname#yourdomain.com - This is where the form will send a message to.
$email_subject = "Formulario de contacto web: $name";
$email_body = "Ha recibido un nuevo mensaje desde la web.\n\n" . "Detalles:\n\Nombre: $name\n\nEmail: $email_address\n\Teléfono: $phone\n\Mensaje:\n$message";
$headers = "From: noreply#yourdomain.com\n"; // This is the email address the generated message will be from. We recommend using something like noreply#yourdomain.com.
$headers .= "Reply-To: $email_address";
mail($to, $email_subject, $email_body, $headers);
return true;
?>
I think GET method is getting wrong data, I fill the form with text strings, but the echo methods are printing 1:
If I fill the form with real strings, why is the echo method printing 1 for each field? Also, I think that the warning is because the parameters are all "1", but this make no sense for me.
You have assigned the value of isset() to the variable:
Determine if a variable is set and is not NULL.
This will return 1 when the variable is set.
$name = isset($_GET['name']);
echo $name;
$email_address = isset($_GET['email']);
echo $email_address;
$phone = isset($_GET['phone']);
echo $phone;
$message = isset($_GET['message']);
echo $message;
The following code will check if the $_GET variable is set, then assign it:
if (isset($_GET['name'])) { $name = $_GET['name'];
echo $name;
}
if (isset($_GET['email'])) { $email_address = $_GET['email'];
echo $email_address;
}
if (isset($_GET['phone'])) { $phone = $_GET['phone'];
echo $phone;
}
if (isset($_GET['message'])) { $message = $_GET['message'];
echo $message;
}
You are printing the return value of isset() and not the array index you are testinging to see if it is set.
$name = isset($_GET['name']);
should be something more along the lines of:
$name = "";
if (isset($_GET['name'])) {
$name = $_GET['name'])
};
or you could use a ternary operator:
$name = (isset($_GET['name'])) ? $_GET['name'] : "";
Your problem is there:
$name = isset($_GET['name']);
echo $name;
Because $_GET exists, isset($_GET['name']) returns 1, which you store in $name. $name is equal to 1 now (or true).
do something like
if(isset($_GET['name']))
{
echo $_GET['name'];
}
You need to use like below:-
if(isset($_GET['name']))
{
$name = $_GET['name'];
}
Related
I am trying to send an email from a enquiry form available on a catalogue website on which I am working and found a strange issue.
On the same domain I have a file to test the email function with following code in it:
$sender = 'someone#somedomain.tld';
$recipient = 'name#gmail.com';
$subject = "php mail test";
$message = "php test message";
$headers = 'From:' . $sender;
if (mail($recipient, $subject, $message, $headers))
{
echo "Message accepted";
}
else
{
echo "Error: Message not accepted";
}
and its working fine. But the same code is not working on the index.php page where I have the enquiry form and also not showing any error at all (I have checked the error log. I have also tried by putting this code in a separate file and by including it on index.php but the same result).
<form name="frm_enquiry" id="frm_enquiry" method="post" autocomplete="off">
<div class="row">
<div class="col-lg-3 col-md-3">
<div class="form-group">
<label for="fullname">Name:</label>
<input type="text" class="form-control" id="fullname" name="fullname" placeholder="Enter your name">
</div>
</div>
<div class="col-lg-3 col-md-3">
<div class="form-group">
<label for="email">Email:</label>
<input type="email" class="form-control" id="email" name="email" placeholder="Enter your email">
</div>
</div>
<div class="col-lg-3 col-md-3">
<div class="form-group">
<label for="mobile">Mobile No:</label>
<input type="text" class="form-control" id="mobile" name="mobile" placeholder="Enter your mobile number">
</div>
</div>
<div class="col-lg-3 col-md-3">
<div class="form-group">
<label style="width: 100%;" for="mobile"> </label>
<button type="submit" class="btn btn-block btn-primary" name="submit">Submit</button>
</div>
</div>
</div>
</form>
php:
if( isset( $_REQUEST['submit'] ) )
{
$name = $_REQUEST['fullname'];
$email = $_REQUEST['email'];
$mobile = $_REQUEST['mobile'];
echo $name . ' : ' . $email . ' : ' . $mobile . '<br>';
$sender = 'someone#somedomain.tld';
$recipient = 'name#gmail.com';
$subject = "php mail test";
$message = "php test message";
$headers = 'From:' . $sender;
if (mail($recipient, $subject, $message, $headers))
{
echo "Message accepted";
}
}
Someone please guide me, what I am doing wrong here, I am stuck on this from last 2 days.
Thanks in advance.
I have written a script mail.php to handle the validation of form data and to send the form data via email. I have been testing this script by entering known invalid data however the script does not echo the error messages and just sends the data anyway.
Here is the form html:
<form method="post" action="mail.php" class="col-12" id="form-book">
<div class="row">
<div class=" form-group col-12">
<p>Fill out the form below to tell me about your problem. <strong>Any problems to do with technology, all the solutions.</strong> Just tell me what you can, however the more info you give the better.</p>
</div>
<div class="form-group col-6">
<label></label>
<input id="name" name="name" placeholder="Name" type="text" required="required" class="form-control here bottom"> <span class="error"> <?php echo $nameErr; echo $nameErrEmpty;?></span>
</div>
<div class="form-group col-6">
<label></label>
<input id="phone" name="phone" placeholder="Phone#" type="text" required="required" class="form-control here bottom"> <span class="error"> <?php echo $phoneErr; echo$phoneErrEmpty;?></span>
</div>
<div class="form-group col-12">
<label></label>
<input id="email" name="email" placeholder="Email (Optional)" type="text" class="form-control here bottom"> <span class="error"> <?php echo $emailErr; echo $emailErrEmpty;?></span>
</div>
<div class="form-group col-6">
<input data-provide="datepicker" id="date" name="date" placeholder="Pick a date" required="required" class="form-control here bottom"> <span class="error"> <?php echo $dateErr; echo $dateErrEmpty;?></span>
</div>
<div class="form-group col-6">
<input type="text" id="time" name="time" placeholder="Choose the best time" required="required" class="form-control here bottom timepicker"> <span class="error"> <?php echo $timeErr; echo $timeErrEmpty;?></span>
</div>
<div class="form-group col-12">
<label></label>
<textarea id="message" name="message" cols="40" rows="5" class="form-control" required="required" aria-describedby="messageHelpBlock"></textarea> <span class="error"> <?php echo $messageErr; echo $messageErrEmpty;?></span>
<span id="messageHelpBlock" class="form-text text-muted">Tell me a little about whats going on or what you need help with.</span>
</div>
<div class="form-group col-12">
<button name="submit" type="submit" class="btn btn-primary">Send your message</button>
</div>
</div>
<!--row-->
</form>
Here is mail.php:
<?php
error_reporting(-1);
ini_set('display_errors', 'On');
set_error_handler("var_dump");
date_default_timezone_set("Pacific/Honolulu");
if (isset($_POST['submit'])) {
$name = $_POST['name'];
$phone = $_POST['phone'];
$email = $_POST['email'];
$date = $_POST['date'];
$time = $_POST['time'];
$message = $_POST['message'];
$subject = "Appointment Booked";
$mailTo = "itguy#johnpuaoi.com";
$email = filter_var($email, FILTER_SANITIZE_EMAIL);
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if (empty($name)) {
$nameErrEmpty = "Your name is required";
} elseif (is_int($name)) {
$nameErr = "That is not a valid name";
} else {
$nameTested = test_input($name);
}
if (empty($phone)) {
$phoneErrEmpty = "Your phone number is required";
} elseif (is_int($name)) {
$phoneTested = test_input($phone);
} else {
$phoneErr = "Phone Number needs to be in this format e.x 1234567890";
}
if (empty($email)) {
$emailErrEmpty = "Your name is required";
} elseif (filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "That is not a valid email";
} else {
$emailTested = test_input($name);
}
if (empty($message)) {
$messageErrEmpty ="You must tell me about your problem";
} else {
$messageTested = test_input($message);
}
$dateTested = test_input($date);
$timeTested = test_input($time);
$headers = "From: ".$emailTested;
$txt = "An appointment was booked by ".$nameTested.".\n\n".$dateTested." #".$timeTested.".\n\n".$messageTested;
mail($mailTo, $subject, $txt, $headers);
header("Location: index.php?mailsend");
}
?>
I have searched stack for similar issues but have found none. I am a total noob to php so any help would be appreciated. Thanks!
This is the code for the form.
<?php
if ($_POST) {
if (isset($_POST["submit"])) {
$name = $_POST['name'];
$email = $_POST['email'];
$company = $_POST['company'];
$phone = $_POST['phone'];
$checkbox = '';
if (isset($_POST['checkbox'])) {
$checkbox = 'Yes';} else{
$checkbox = 'No' ;}
$message = $_POST['message'];
$from = 'Demo Contact Form';
$to = 'imvael#gmail.com, vnikolic1#cps.edu';
$subject = 'Message from Contact Demo ';
$body ="From: $name\n E-Mail: $email\n Company: $company\n Phone: $phone\n Opt In?: $checkbox\n Message:\n $message";
$headers = 'From: webmaster#bradfordsystems.com' . "\r\n" .
'Reply-To: ' .$email . "\r\n" .
'X-Mailer: PHP/' . phpversion();
// Check if name has been entered
if (!$_POST['name']) {
$errName = 'Please enter your name';
}
// Check if email has been entered and is valid
if (!$_POST['email'] || !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$errEmail = 'Please enter a valid email address';
}
// Check if name has been entered
if (!$_POST['phone']) {
$errName = 'Please enter your phone number';
}
//Check if message has been entered
if (!$_POST['message']) {
$errMessage = 'Please enter your message';
}
// then after the posting of the form data
// validation
// If there are no errors, send the email
if (!$errName && !$errEmail && !$errMessage && isset($_POST['url']) && $_POST['url'] == '') {
if (mail ($to, $subject, $body, $headers)) {
header("Location: thankyou.php"); /* Redirect browser */
exit();
} else {
$result='<div class="alert alert-danger">Sorry there was an error sending your message. Please try again later.</div>';
}
}
}
header("Location: " . $_SERVER['REQUEST_URI']);
exit();
}
This is the form itself
<div class="wrapper">
<div class="row">
<div class="col _66">
<?php echo $result; ?>
<form role="form" name="contactForm" id="contactForm" method="post" action="contact.php#contactForm">
<p>
We welcome your feedback and inquiries. Please use the form below to get in touch.
</p>
<div class="row">
<div class="col">
<input type="text" id="name" name="name" placeholder="Name" value="<?php echo htmlspecialchars($_POST['name']); ?>" required>
<?php echo "<p class='text-danger'>$errName</p>";?>
</div>
<div class="col">
<input type="email" id="email" name="email" placeholder="Company Email" value="<?php echo htmlspecialchars($_POST['email']); ?>" required>
<?php echo "<p class='text-danger'>$errEmail</p>";?>
</div>
</div>
<div class="row">
<div class="col">
<input type="text" id="company" name="company" placeholder="Company" value="<?php echo htmlspecialchars($_POST['company']); ?>" required>
</div>
<div class="col">
<input type="tel" id="phone" name="phone" <?php echo htmlspecialchars($_POST['phone']); ?> placeholder="Phone" required>
<?php echo "<p class='text-danger'>$errPhone</p>";?>
</div>
</div>
<div class="row">
<div class="col">
<input type="number" id="zipcode" name="zipcode" placeholder="Zip Code" value="<?php echo htmlspecialchars($_POST['zipcode']); ?>">
</div>
<div class="col">
<input id="checkBox" type="checkbox"> <span id="optInText">YES, I want a Free Workspace Evaluation!</span>
</div>
</div>
<div class="row">
<div class="col">
<p class="antispam">Leave this empty: <input type="text" name="url" /></p>
</div>
</div>
<div class="row">
<div class="col submit-col">
<p>Questions or Comments?</p>
<textarea id="message" name="message" placeholder="Enter your questions or comments here" style="height:200px"> <?php echo htmlspecialchars($_POST['message']); ?></textarea>
<?php echo "<p class='text-danger'>$errMessage</p>";?>
<button class="btn btn-dark hvr-underline-from-left" name="submit" type="submit" value="Send">Submit Request</button>
</div>
</div>
</form>
</div>
</div>
</section>
I am writing a contact form script from scratch The code is working correctly, but I am unable to prevent resubmissions if they user refreshed the page or press the submit buton more then once.
Also is it a bad practice to use self submitting contact forms?
I am receiving empty email from Submit form every day around the same time.
Form Code :
<div class="form">
<h4 class="h-light text-center">Submit a Query</h4>
<form class="form-horizontal" action="sendemail.php" method="post" id="contact_form">
<!-- Text input-->
<div class="form-group">
<label class="col-sm-2 control-label">Name</label>
<div class="col-sm-10 inputGroupContainer">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
<input name="name" placeholder="Name" class="form-control input-text" type="text" required>
</div>
</div>
</div>
<!-- Text input-->
<div class="form-group">
<label class="col-sm-2 control-label">E-Mail</label>
<div class="col-sm-10 inputGroupContainer">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-envelope"></i></span>
<input name="email" placeholder="E-Mail Address" class="form-control input-text" type="email" required>
</div>
</div>
</div>
<!-- Text input-->
<div class="form-group">
<label class="col-sm-2 control-label">Phone #</label>
<div class="col-sm-10 inputGroupContainer">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-earphone"></i></span>
<input name="phone" placeholder="(123)456-7890" class="form-control input-text" type="text" required>
</div>
</div>
</div>
<!-- Text area -->
<div class="form-group">
<label class="col-sm-2 control-label">Message</label>
<div class="col-sm-10 inputGroupContainer">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-pencil"></i></span>
<textarea class="form-control input-text text-area" name="message" placeholder="Enter your massage for us here. We will get back to you." required></textarea>
</div>
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label"><img src="media/home/captcha.png"></label>
<div class="col-sm-10">
<div class="input-group">
<div class="g-recaptcha" data-sitekey="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"></div>
</div>
</div>
</div>
<!-- Success message -->
<div class="alert alert-success" role="alert" id="success_message">Success <i class="glyphicon glyphicon-thumbs-up"></i> Thanks for contacting us, we will get back to you shortly.</div>
<!-- Button -->
<div class="form-group">
<label class="col-sm-4 control-label"></label>
<div class="col-sm-8">
<button type="submit" class="input-btn" >Send <span class="glyphicon glyphicon-send"></span></button>
</div>
</div>
</form>
sendemail.php Code:
<?php
/* These are the variable that tell the subject of the email and where the email will be sent.*/
$emailSubject = 'New query !';
$mailto = 'xxx#domain.in';
/* These will gather what the user has typed into the field. */
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$message = $_POST['message'];
/* This takes the information and lines it up the way you want it to be sent in the email. */
$body = <<<EOD
<br><hr><br>
Name: $name <br>
Email Address: $email <br>
Phone Number: $phone <br>
Message: $message<br>
EOD;
$headers = "From:domain.in<xxx#domain.in>\r\n"; // This takes the email and displays it as who this email is from.
$headers .= "Content-type: text/html\r\n"; // This tells the server to turn the coding into the text.
//$success = mail($mailto, $emailSubject, $body, $headers); // This tells the server what to send.
if(mail($mailto, $emailSubject, $body, $headers))
{
echo "Your query has been submitted successfully. ";
echo 'Go Back';
}
else
{
echo "Failure";
}
?>
I have no idea what is going on, the code seems to be fine, but still i am receiving that empty email only with the field name like...
Name :
Email Address :
Phone Number :
Message :
But no information filled in it.
Thanks in advance.
Validate the input on the PHP side before you send the email. eg:
$valid = true;
$name = $_POST['name'];
if(empty($name))
{
echo('Please enter your name');
$valid = false;
}
// Repeat for other fields
if($valid)
{
// Send the email
}
I am not so good with PHP, please let me know if it correct.. Thank you
<?php
/* These are the variable that tell the subject of the email and where the email will be sent.*/
$emailSubject = 'New query!';
$mailto = 'xxx#domain.in';
/* These will gather what the user has typed into the fieled. */
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$message = $_POST['message'];
/* This takes the information and lines it up the way you want it to be sent in the email. */
$body = <<<EOD
<br><hr><br>
Name: $name <br>
Email Address: $email <br>
Phone Number: $phone <br>
Message: $message<br>
EOD;
$headers = "From:domain.in<info#domain.in>\r\n"; // This takes the email and displays it as who this email is from.
$headers .= "Content-type: text/html\r\n"; // This tells the server to turn the coding into the text.
//$success = mail($mailto, $emailSubject, $body, $headers); // This tells the server what to send.
$valid = true;
$name = $_POST['name'];
if(empty($name))
{
echo('Please enter your name');
$valid = false;
}
$email = $_POST['email'];
if(empty($email))
{
echo('Please enter your email');
$valid = false;
}
$phone = $_POST['phone'];
if(empty($phone))
{
echo('Please enter your Phone number');
$valid = false;
}
$message = $_POST['message'];
if(empty($message))
{
echo('Please enter your message');
$valid = false;
}
if($valid)
{
if(mail($mailto, $emailSubject, $body, $headers))
{
echo "Your query has been submitted successfully. ";
echo 'Go Back';
}
}
else
{
echo "Failure";
}
i
?>
Should be working now?
$valid = true;
$name = $_POST['name'];
if(empty($name))
{
echo('Please enter your name');
$valid = false;
}
<br/>
$email = $_POST['email'];
if(empty($email))
{
echo('Please enter your email');
$valid = false;
}
<br/>
$phone = $_POST['phone'];
if(empty($phone))
{
echo('Please enter your Phone number');
$valid = false;
}
<br/>
$message = $_POST['message'];
if(empty($message))
{
echo('Please enter your message');
$valid = false;
}
<br/>
if($valid)
{
if(mail($mailto, $emailSubject, $body, $headers))
{
echo "Your query has been submitted successfully. ";
echo 'Go Back';
}
}
else
{
echo "Failure";
}
?>
Checking for whether $_Post is empty is the usual and logical way to go.
But for someone who is curious about why the same empty email is being sent to you everyday (usually it's some kind of bot) why not add the following fields in your message body so you know what's happening.
This way you learn how the web works better too.
For example
$ip = $_SERVER['REMOTE_ADDR']; // for IP address
$browser = $_SERVER['HTTP_USER_AGENT']; // get browser info
and you add above info to your message body so you know what's going on.
I'm trying to send an email via HTML5 with bootstrap + php.
HTML:
<form name="frmContacto" class="form-horizontal" method="post" action="mail/contact_me.php">
<fieldset>
<legend class="text-center header">Formulario de contacto</legend>
<div class="form-group">
<span class="col-md-1 col-md-offset-2 text-center"><i class="fa fa-user bigicon"></i></span>
<div class="col-md-8">
<input id="fname" name="name" type="text" placeholder="Nombre" class="form-control">
</div>
</div>
<div class="form-group">
<span class="col-md-1 col-md-offset-2 text-center"><i class="fa fa-user bigicon"></i></span>
<div class="col-md-8">
<input id="lname" name="name" type="text" placeholder="Apellidos" class="form-control">
</div>
</div>
<div class="form-group">
<span class="col-md-1 col-md-offset-2 text-center"><i class="fa fa-envelope-o bigicon"></i></span>
<div class="col-md-8">
<input id="email" name="email" type="text" placeholder="Correo electrónico" class="form-control">
</div>
</div>
<div class="form-group">
<span class="col-md-1 col-md-offset-2 text-center"><i class="fa fa-phone-square bigicon"></i></span>
<div class="col-md-8">
<input id="phone" name="phone" type="text" placeholder="Teléfono" class="form-control">
</div>
</div>
<div class="form-group">
<span class="col-md-1 col-md-offset-2 text-center"><i class="fa fa-pencil-square-o bigicon"></i></span>
<div class="col-md-8">
<textarea class="form-control" id="message" name="message" placeholder="Introduce aquí tu mensaje." rows="7"></textarea>
</div>
</div>
<div class="form-group">
<div class="col-md-12 text-center">
<a href="mailto:xxx#example.com?Subject=Hello%20again" target="_top">
<button type="submit" class="btn btn-primary btn-lg">Enviar</button>
</a>
</div>
</div>
</fieldset>
</form>
PHP:
<?php
// Check for empty fields
if (empty($_POST['name']) ||
empty($_POST['email']) ||
empty($_POST['phone']) ||
empty($_POST['message']) ||
!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)
) {
echo "No arguments Provided!";
return false;
}
$name = $_POST['name'];
$email_address = $_POST['email'];
$phone = $_POST['phone'];
$message = $_POST['message'];
// Create the email and send the message
$to = 'xxx#gmail.com'; // Add your email address inbetween the '' replacing yourname#yourdomain.com - This is where the form will send a message to.
$email_subject = "Formulario de contacto web: $name";
$email_body = "Ha recibido un nuevo mensaje desde la web.\n\n" . "Detalles:\n\Nombre: $name\n\nEmail: $email_address\n\Teléfono: $phone\n\Mensaje:\n$message";
$headers = "From: noreply#yourdomain.com\n"; // This is the email address the generated message will be from. We recommend using something like noreply#yourdomain.com.
$headers .= "Reply-To: $email_address";
mail($to, $email_subject, $email_body, $headers);
return true;
?>
I don't know if I have to import something in the HTML. It seems that the php mail() function is not being called, since I have a breakpoint in the function line and nothing happens when I click the "Submit" button. Also, the email is the same in $to php function and in the HTML "mailto".
Thanks a lot.
Check the following things-
1. In your HTML you have declared Name Line of form twice, which is not required.
2. You should have setting in your server/PHP configuration file configured to a mail Server. Without Mail server connected, you can't send mails
Have you validate your settings in php.ini (sendmail parameter) ?
You might read this if needed:
https://blog.codinghorror.com/so-youd-like-to-send-some-email-through-code/
The Code is below is well commented so there is no point writing much. Just read through the Comments. It is quite self-explanatory:
PHP
<?php
// GET ALL POSTED FIELD-VALUES AND ASSIGN THEM DEFAULT VALUES OF NULL (IF THEY ARE NOT YET SET...
$lastName = isset($_POST['last_name']) ? htmlspecialchars(trim($_POST['last_name'])) : null;
$firstName = isset($_POST['first_name']) ? htmlspecialchars(trim($_POST['first_name'])) : null;
$email = isset($_POST['email']) ? htmlspecialchars(trim($_POST['email'])) : null;
$phone = isset($_POST['phone']) ? htmlspecialchars(trim($_POST['phone'])) : null;
$message = isset($_POST['message']) ? htmlspecialchars(trim($_POST['message'])) : null;
// VALIDATE THE FIELDS: BUT FIRST CREATE AN ARRAY
// TO HOLD ERROR MESSAGES FOR FIELDS THAT FAILED THE VALIDATION.
$arrErrorBag = array();
$strErrorMessage = "";
// VALIDATE E-MAIL:
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$arrErrorBag["E-Mail"] = "The Email you entered in not valid.";
}
// VALIDATE FIRST NAME:
if(!preg_match('#(^[a-zA-z])?([\w\.\-\ ])*\w*$#i', $firstName)){
$arrErrorBag["First Name"] = "First Name Should not be Empty and should contain only alpha-numeric Characters.";
}
// VALIDATE LAST NAME:
if(!preg_match('#(^[a-zA-z])?([\w\.\-\ ])*\w*$#i', $lastName)){
$arrErrorBag["Last Name"] = "Last Name Should not be Empty and should contain only alpha-numeric Characters.";
}
// VALIDATE PHONE:
if(!preg_match('#^(\+\d{1,3})?\s?(\d{2,4})\s?(\d{2,4})\s?(\d{2,4})\s?(\d{2,4})$#', $phone)){
$arrErrorBag["Phone"] = "Telephone Number should be Numeric and Should not be Empty.";
}
// VALIDATE MESSAGE:
if(!preg_match('#([\w\.\-\d\ ])*\w*$#si', $name)){
$arrErrorBag["Message"] = "Message Should not be Empty and should contain only alpha-numeric Characters only.";
}
if(!empty($arrErrorBag)){
// WE HAVE SOME ERRORS SO WE BUILD A STRING MESSAGE BASED ON THE ERRORS WE HAVE GATHERED ABOVE...
$strErrorMessage .= "<h6 class='error-heading'>There are Errors in the Form Please, correct them to continue.</h6>";
foreach($arrErrorBag as $fieldName=>$errorMessage){
$strErrorMessage .= "<div class='error-block'><strong>{$fieldName}: </strong>";
$strErrorMessage .= "<span>{$errorMessage}: </span></div>";
}
}else{
// THE FORM IS CLEAN AND VALID SO WE SEND THE E-MAIL:
$name = $firstName . " " . $lastName;
$to = 'xxx#gmail.com'; // Add your email address inbetween the '' replacing yourname#yourdomain.com - This is where the form will send a message to.
$email_subject = "Formulario de contacto web: $name";
$email_body = "Ha recibido un nuevo mensaje desde la web.\n\n" . "Detalles:\n\Nombre: {$name}\n\nEmail: {$email}\n\Teléfono: {$phone}\n\Mensaje:\n{$message}";
$headers = "From: noreply#yourdomain.com\n"; // This is the email address the generated message will be from. We recommend using something like noreply#yourdomain.com.
$headers .= "Reply-To: {$email}";
mail($to, $email_subject, $email_body, $headers);
// THE MAIL WAS SENT SO YOU CAN NOW REDIRECT TO ANOTHER PAGE... MAYBE A THANK YOU PAGE...
$redirectURL = "thank-you.php"; //<== THIS IS ONLY AN EXAMPLE... THE URL SHOULD RATHER BE ANY PAGE OF YOUR CHOOSING.
header("location: " . $redirectURL);
}
?>
HTML
<!-- BEFORE THE FORM, CREATE A DIV TO HOLD ERROR MESSAGE, IN CASE ERRORS OCCUR... -->
<!-- IN THIS SCENARIO, IT IS IDEAL TO HAVE BOTH THE PHP AND THE HTML INSIDE THE SAME FILE... -->
<!-- THE PHP CODE SHOLD BE AT THE TOP OF THE FILE & THE HTML MARKUP BELOW... -->
<!-- NOTICE THAT THE ACTION ATTRIBUTE OF THE FORM IS NOW EMPTY... THIS FORCES THE FORM TO SUBMIT BACK TO ITSELF: THIS PAGE... -->
<div class="error-msg-wrapper"><?php echo $strErrorMessage; ?></div>
<form name="frmContacto" class="form-horizontal" method="post" action="">
<fieldset>
<legend class="text-center header">Formulario de contacto</legend>
<div class="form-group">
<span class="col-md-1 col-md-offset-2 text-center">
<i class="fa fa-user bigicon"></i>
</span>
<div class="col-md-8">
<input id="fname" name="first_name" type="text" placeholder="Nombre" value="<?php echo $firstName; ?>" class="form-control">
</div>
</div>
<div class="form-group">
<span class="col-md-1 col-md-offset-2 text-center">
<i class="fa fa-user bigicon"></i>
</span>
<div class="col-md-8">
<input id="lname" name="last_name" type="text" placeholder="Apellidos" value="<?php echo $lastName; ?>" class="form-control">
</div>
</div>
<div class="form-group">
<span class="col-md-1 col-md-offset-2 text-center">
<i class="fa fa-envelope-o bigicon"></i>
</span>
<div class="col-md-8">
<input id="email" name="email" type="text" placeholder="Correo electrónico" value="<?php echo $email; ?>" class="form-control">
</div>
</div>
<div class="form-group">
<span class="col-md-1 col-md-offset-2 text-center">
<i class="fa fa-phone-square bigicon"></i>
</span>
<div class="col-md-8">
<input id="phone" name="phone" type="text" placeholder="Teléfono" value="<?php echo $phone; ?>" class="form-control">
</div>
</div>
<div class="form-group">
<span class="col-md-1 col-md-offset-2 text-center">
<i class="fa fa-pencil-square-o bigicon"></i>
</span>
<div class="col-md-8">
<textarea class="form-control" id="message" name="message" placeholder="Introduce aquí tu mensaje." rows="7"><?php echo $message; ?></textarea>
</div>
</div>
<div class="form-group">
<div class="col-md-12 text-center">
<input type="submit" class="btn btn-primary btn-lg" value="Enviar" />
</div>
</div>
</fieldset>
</form>