I have been trying to implement server validation to prevent blank emails in my contact us page, but I am not sure on how to do it in PHP, here is my code:
<?php
$field_name = $_POST['cf_name'];
$field_email = $_POST['cf_email'];
$field_tel = $_POST['cf_tel'];
$field_message = $_POST['cf_message'];
$mail_to = 'test#test.com, test#test.com, test#test.com';
$subject = 'Just iStuff Mobile Contact Us: '.$field_name;
$body_message = 'From: '.$field_name."\n";
$body_message .= 'E-mail: '.$field_email."\n";
$body_message .= 'Telephone Number: '.$field_tel."\n";
$body_message .= 'Message: '.$field_message;
$headers = 'From: '.$field_email."\r\n";
$headers .= 'Reply-To: '.$field_email."\r\n";
$mail_status = mail($mail_to, $subject, $body_message, $headers);
if ($mail_status) { ?>
<script language="javascript" type="text/javascript">
alert('Thank you for your email, we have received your message and will reply within the next few days.');
window.location = 'contactus.html';
</script>
<?php
}
else { ?>
<script language="javascript" type="text/javascript">
alert('Message failed, please try again or email test#test.com');
window.location = 'contactus.html';
</script>
<?php
}
?>
Can anyone help me to do this, the tutorials online do not cover this way of doing it...
Thanks
Before your $mail_to..
You can validate the _POST/_GET first on server side.
<?php
if (empty($field_name) && empty($field_email) && empty($field_tel) && empty($field_message)) {
echo 'Please correct the fields';
return false;
}
?>
Alternatively, you can validate first on the client-side. It will save you time and resources.
just test the variable for "emptiness" and exit early. Something like this:
if(empty($field_email)) {
// maybe show the user a reason why this was rejected...
return;
}
You probably want to do this for just about all the input fields.
In addition, you can use JavaScript (jQuery has some nice plugins) to prevent the user from submitting invalid data in the first place. This won't remove the need to do it server side (since they can just disable JS, or someone malicious might intentionally bypass this measure), but it can make it a more user friendly experience.
You can use filter for this; since you're using the passed email address as part of the mail() operation, it's best to also validate:
$fields = filter_input_array(INPUT_POST, array(
'name' => FILTER_UNSAFE_RAW,
'email' => FILTER_VALIDATE_EMAIL,
'tel' => FILTER_UNSAFE_RAW,
'message' => FILTER_UNSAFE_RAW,
));
// check for missing fields
if (null === $fields || in_array(null, $fields, true)) {
// some or all fields missing
} elseif (in_array(false, $fields, true)) {
// some or all fields failed validation
} else {
// all fields passed validation
// use $fields['email'] as the email address
}
I've used FILTER_UNSAFE_RAW for all fields except email, but perhaps there are better filters that apply.
Try to put a submit input <input type="submit" name="sub" value="Submited"> inside your form
when it's clicked.
<?php
if (isset($_POST['sub']) {
$field_name = $_POST['cf_name'];
$field_email = $_POST['cf_email'];
$field_tel = $_POST['cf_tel'];
$field_message = $_POST['cf_message'];
if (empty($field_name) && ....)
{
exit('Field name is empty');
}
.....
Related
<!-- PHP CONTACT FORM -->
<?php
$look = $_POST['look'];
$design = $_POST['design'];
$old_website = $_POST['old_website'];
$redesign = $_POST['redesign'];
?>
<?php
$field_name = $_POST['user_name'];
$field_email = $_POST['user_email'];
$field_message = $_POST['user_message'];
$mail_to = 'alzirabarretto#gmail.com';
$subject = 'Queries';
$body_message = 'From: '.$field_name."\n";
$body_message .= 'E-mail: '.$field_email."\n";
$body_message .= 'Message: '.$field_message;
$headers = 'From: '.$field_email."\r\n";
$headers .= 'Reply-To: '.$field_email."\r\n";
$mail_status = mail($mail_to, $subject, $body_message, $headers);
if ($mail_status) { ?>
<script language="javascript" type="text/javascript">
alert('Thank you for the message.');
window.location = '/website_form.html';
</script>
<?php
}
else { ?>
<script language="javascript" type="text/javascript">
alert('Message failed. Please, send an email to alzirabarretto#gmail.com');
window.location = '/website_form.html';
</script>
<?php
}
?>
I update the php code. When sending the mail it works fine but i don't understand when I didn't received my mail. I have change the radio value according what you have said. And what about the url which I create the input type? I'm bit little confused how to do in php code.
I think this line is wrong.
$radio = $_POST['look' , 'design', 'old_website' , 'redesign'];
Try capturing them separately like this,
$look = $_POST['look'];
$design = $_POST['design'];
$old_website = $_POST['old_website'];
$redesign = $_POST['redesign'];
And even for radio group LOOK, try changing the corresponding values. Or you will get value as radio_1,radio_2, ...
I am new to JQuery and havent used AJAX at all. I have searched the web for days with no complete answer.
Im trying to have a form be emailed via AJAX while JQuery hides the form and displays additional data. The JQuery portions works as the pages switches to display the proper data but the form information doesnt get emailed.
JQuery/AJAX
$(document).ready(function() {
//When the form is submitted...
$('form').on('submit',function(e) {
//Send the serialized data to mailer.php.
$.ajax({
url:'mailer.php',
data:$(this).serialize(),
type:'POST',
success:function(data){
console.log(data);
$("#success").show().fadeOut(5000); //=== Show Success Message==
},
error:function(data){
$("#error").show().fadeOut(5000); //===Show Error Message====
}
});
e.preventDefault(); //=== To Avoid Page Refresh and Fire the Event "Click"===
//$.post("mailer.php");
//Take our response, and replace whatever is in the "form2"
//div with it.
$('#form1').hide();
$('#form2').show();
});
});
PHP Submit file mailer.php
<?php
//Grab Posted Data
$fname = strip_tags(htmlentities($_POST['fname']));
$lname = strip_tags(htmlentities($_POST['lname']));
$name = $fname." ".$lname;
$email = strip_tags($_POST['email']);
$phone = strip_tags(htmlentities($_POST['phone']));
$address = strip_tags(htmlentities($_POST['address']));
$city = strip_tags(htmlentities($_POST['city']));
$state = strip_tags(htmlentities($_POST['state']));
$zip = strip_tags(htmlentities($_POST['zip']));
$country = strip_tags(htmlentities($_POST['country']));
$message = strip_tags(htmlentities($_POST['goals']));
// PREPARE THE BODY OF THE MESSAGE
$message = '<html><body>';
$message .= '<table rules="all" style="border-color: #666;" cellpadding="10">';
$message .= "<tr style='background: #eee;'><td><strong>Name:</strong> </td><td>$name</td></tr>";
$message .= "<tr><td><strong>Email:</strong> </td><td>$email</td></tr>";
$message .= "<tr><td><strong>Phone:</strong> </td><td>$phone</td></tr>";
$message .= "<tr><td><strong>Address:</strong> </td><td>$address</td></tr>";
$message .= "<tr><td> </td><td>$city, $state $zip $country</td></tr>";
$message .= "<tr><td><strong>Goals:</strong> </td><td>$message</td></tr>";
$message .= "</table>";
$message .= "</body></html>";
// CHANGE THE BELOW VARIABLES TO YOUR NEEDS
$to = 'me#me.com';
$subject = 'Website Change Reqest';
$headers = "From: $email \r\n";
$headers .= "Reply-To: $email \r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
if (mail($to, $subject, $message, $headers)) {
echo 'Your message has been sent.';
} else {
echo 'There was a problem sending the email.';
}
?>
PHP mail() uses sendmail system, and most of the problems happens when it is not set up properly. Sometimes webhosters disable it outright.
Sometimes, i solved this problem by using an external library, PhpMailer, for example, and SMTP with a real mail account.
On a side note - never ever do this:
$fname = strip_tags(htmlentities($_POST['fname']));
$lname = strip_tags(htmlentities($_POST['lname']));
$name = $fname." ".$lname;
$email = strip_tags($_POST['email']);
$phone = strip_tags(htmlentities($_POST['phone']));
$address = strip_tags(htmlentities($_POST['address']));
$city = strip_tags(htmlentities($_POST['city']));
$state = strip_tags(htmlentities($_POST['state']));
$zip = strip_tags(htmlentities($_POST['zip']));
$country = strip_tags(htmlentities($_POST['country']));
$message = strip_tags(htmlentities($_POST['goals']));
It can be easily replaced by something like:
extract(
array_map(
function($elem) {
return strip_tags(html_entities($elem));
}, $_POST)
);
I've already got a problem like this. The issue was not in javascript code, but in php's mail() function.
Happened that nowadays most mail servers do not support unauthenticated e-mail to be sent. See that in order to use mail() function you never provided an username or password to log in a mail server.
My issue was solved using the PHPMailer class (available at http://phpmailer.worxware.com), in witch I provide mailserver's address, account username and password. Thought it is quite easy to create an HTML e-mail with attachments without worry about writing long header codes.
Did you use Denwer for test this example?
I've been looking around for ages and haven't found an easy way of editing this code so that when the user hasn't typed anything into a required field (all of the fields are required) an alert is shown asking the user to please enter something.
Can anyone help?
<?php
$field_name = $_POST['name'];
$field_email = $_POST['email'];
$field_message = $_POST['message'];
$mail_to = 'you#yourdomain.com';
$subject = 'Site Mail';
$body_message = 'From: '.$field_name."\n";
$body_message .= 'Email: '.$field_email."\n";
$body_message .= 'Message: '.$field_message;
$headers = 'From: '.$field_email."\r\n";
$headers .= 'Reply-To: '.$field_email."\r\n";
$mail_status = mail($mail_to, $subject, $body_message, $headers);
if ($mail_status) { ?>
<script language="javascript" type="text/javascript">
alert('Thanks! Your email has been sent.');
window.location = 'index.html';
</script>
<?php
}
else { ?>
<script language="javascript" type="text/javascript">
alert('Sorry, something went wrong.');
window.location = 'index.html';
</script>
<?php
}
?>
You can use required attribute if you want to take advantage of html5 features.
Try this LINK. It shows a simple demo of how to use the required attribute.
This one too
PHP
<?php
$fields = array([0]=>$field_name,[1]=>$field_email,[2]=>$field_message);
foreach($fields as $field){
if !$field{
echo "Please enter a value.";
}
}
?>
Alternatively, you could use javascript validation, that would look something like this:
<script>
function formValid(){
var valid = true;
var fields = getElementByTag(input);
for (var i;i>=fields.length;i++){
if (!fields[i]){
getElementById('warning').style.display='inline'; // assuming the error message element is called 'warning'
getElementById('valid').value=1; // assuming we have an input that will indicate to the php code whether the form is validated
}
}
}
</script>
for this script we would then add to the beginning of the form-action php block:
if(isset($_POST['submit'])&&$_POST['valid']!=1){
// form action code goes here
}
use the code like below:-
$('.required').each(function(){
if($(this).val()=="")
{
alert("error");
}
});
The most common way to check for required fields is both on the client side (to inform the user) and the server side (to check the data is legit before we send it).
On the client side, at the point at which the form is submitted we should check to see if the fields are correct and ask the user to fix mistakes. There are a bunch of great helper libraries available to do this, a couple of the more common libraries are http://parsleyjs.org/ and http://jqueryvalidation.org/ both use jQuery and have easy examples to get started.
On the server side, as some commenters have noted, your current script is vulnerable to header injection and other nasty stuff. You might want to switch to using a library such as swiftmailer which will prevent a lot of bad stuff happening. Here is a really simple example of how to send email http://swiftmailer.org/docs/sending.html
To add server side validation to you example, as simple approach would be to check the values of $_POST['name']; before calling $mailer->send($message);
I'm very new to PHP and am using a basic template 'send-mail' form on a contact page.
It's been requested that I send the email out to multiple email addresses when the "Submit" button is clicked. I've searched around & haven't quite found what I needed. What code do I need to add into the form below in order to send this out to multiple email addresses?
<?php
$mail_to = 'daniel30293#gmail.com'; // specify your email here
// Assigning data from the $_POST array to variables
$name = $_POST['sender_name'];
$mail_from = $_POST['sender_email'];
$phone = $_POST['sender_phone'];
$web = $_POST['sender_web'];
$company = $_POST['sender_company'];
$addy = $_POST['sender_addy'];
$message = $_POST['sender_message'];
// Construct email subject
$subject = 'Web Prayer Request from ' . $name;
// Construct email body
$body_message = 'From: ' . $name . "\r\n";
$body_message .= 'E-mail: ' . $mail_from . "\r\n";
$body_message .= 'Phone: ' . $phone . "\r\n";
$body_message .= 'Prayer Request: ' . $message;
// Construct email headers
$headers = 'From: ' . $name . "\r\n";
$headers .= 'Reply-To: ' . $mail_from . "\r\n";
$mail_sent = mail($mail_to, $subject, $body_message, $headers);
if ($mail_sent == true){ ?>
<script language="javascript" type="text/javascript">
alert('Your prayer request has been submitted - thank you.');
window.location = 'prayer-request.php';
</script>
<?php } else { ?>
<script language="javascript" type="text/javascript">
alert('Message not sent. Please, notify the site administrator admin#bondofperfection.com');
window.location = 'prayer-request.php';
</script>
<?php
}
?>
Your help is greatly appreciated.
You implode an array of recipients:
$recipients = array('jack#gmail.com', 'jill#gmail.com');
mail(implode(',', $recipients), $submit, $message, $headers);
See the PHP: Mail function reference - http://php.net/manual/en/function.mail.php
Receiver, or receivers of the mail.
The formatting of this string must comply with ยป RFC 2822. Some examples are:
user#example.com
user#example.com, anotheruser#example.com
User <user#example.com>
User <user#example.com>, Another User <anotheruser#example.com>
Just add multiple recipients comma seperated in your $mail_to variable like so:
$mail_to = 'nobody#example.com,anotheruser#example.com,yetanotheruser#example.com';
See
mail() function in PHP
Here is a simple example:
<?php
// Has the form been submitted?
// formSubmit: <input type="submit" name="formSubmit">
if (isset($_POST['formSubmit'])) {
// Set some variables
$required_fields = array('name', 'email');
$errors = array();
$success_message = "Congrats! Your message has been sent successfully!";
$sendmail_error_message = "Oops! Something has gone wrong, please try later.";
// Cool the form has been submitted! Let's loop through the required fields and check
// if they meet our condition(s)
foreach ($required_fields as $fieldName) {
// If the current field in the loop is NOT part of the form submission -OR-
// if the current field in the loop is empty, then...
if (!isset($_POST[$fieldName]) || empty($_POST[$fieldName])) {
// add a reference to the errors array, indicating that these conditions have failed
$errors[$fieldName] = "The {$fieldName} is required!";
}
}
// Proceed if there aren't any errors
if (empty($errors)) {
$name = htmlspecialchars(trim($_POST['name']), ENT_QUOTES, 'UTF-8' );
$email = htmlspecialchars(trim($_POST['email']), ENT_QUOTES, 'UTF-8' );
// Email Sender Settings
$to_emails = "anonymous1#example.com, anonymous2#example.com";
$subject = 'Web Prayer Request from ' . $name;
$message = "From: {$name}";
$message .= "Email: {$email}";
$headers = "From: {$name}\r\n";
$headers .= "Reply-To: {$email}\r\n";
$headers .= 'X-Mailer: PHP/' . phpversion();
if (mail($to_emails, $subject, $message, $headers)) {
echo $success_message;
} else {
echo $sendmail_error_message;
}
} else {
foreach($errors as $invalid_field_msg) {
echo "<p>{$invalid_field_msg}</p>";
}
}
}
I've had something strange happen lately with php script I use to send emails from an online contact form and just wondered if any one could shed a little light on the issue.
I've had a php script which I use on multiple websites and it has always worked fine, but for some strange reason, I tried using in on one site and it just wasn't working.
I tried fiddleing with it and eventually realised that it was something to do with the following section of code:
this is the original section of code that usually works fine, but wasn't working for some reason:
$to = 'My Name <info#mydomain.com>';
I then removed the name bit, so that the code looked like this:
$to = 'info#mydomain.com';
and now it sends the email through ok.
As I say, the top code usually works fine, so any ideas why this time I had to alter the code to get it to work?
Any possible explanations would be great :o)
Here's the full code:
<?php
require("is_email.php"); // email validation function
//Retrieve form data.
//GET - user submitted data using AJAX
//POST - in case user does not support javascript, we'll use POST instead
$name = ($_GET['name']) ?$_GET['name'] : $_POST['name'];
$email = ($_GET['email']) ?$_GET['email'] : $_POST['email'];
$telephone = ($_GET['telephone']) ?$_GET['telephone'] : $_POST['telephone'];
$address = ($_GET['address']) ?$_GET['address'] : $_POST['address'];
$enquiry = ($_GET['enquiry']) ?$_GET['enquiry'] : $_POST['enquiry'];
$calculation = ($_GET['calculation']) ?$_GET['calculation'] : $_POST['calculation'];
//flag to indicate which method it uses. If POST set it to 1
if ($_POST) $post=1;
//Server side validation for POST data
if (!$name) $errors[count($errors)] = 'Please click back and enter your name.';
if (!$email) $errors[count($errors)] = 'Please click back and enter your email.';
else if (!is_email($email)) $errors[count($errors)] = 'Please click back as you may have entered an invalid email address.';
if (!$telephone) $errors[count($errors)] = 'Please click back and enter your telephone number.';
if (!$address) $errors[count($errors)] = 'Please click back and enter your address.';
if (!$enquiry) $errors[count($errors)] = 'Please click back and enter your enquiry.';
if ($calculation != '14') $errors[count($errors)] = 'Please click back and check you have correctly answered the simple calculation (in number format).';
//if the errors array is empty, send the mail
if (!$errors) {
//recipient - change this to your name and email
$to = 'info#mydomain.com';
//sender
$from = $name . ' <' . $email . '>';
//subject and the html message
$subject = 'Website Enquiry: ' . $name;
$email_body = '
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head></head>
<body>
<table cellpadding="5" style="color:#757575;">
<tr><td style="color:#3b5998;">Name: </td><td>' . $name . '</td></tr>
<tr><td style="color:#3b5998;">Email: </td><td>' . $email . '</td></tr>
<tr><td style="color:#3b5998;">Telephone: </td><td>' . $telephone . '</td></tr>
<tr valign="top"><td style="color:#3b5998;">Address: </td><td>' . nl2br($address) . '</td></tr>
<tr valign="top"><td style="color:#3b5998;">Enquiry: </td><td>' . nl2br($enquiry) . '</td></tr>
</table>
</body>
</html>';
//send the mail
$result = sendmail($to, $subject, $email_body, $from);
//if POST was used, display the message straight away
if ($_POST) {
if ($result) echo 'Thank you! We have received your message.<br /><br />OK';
else echo 'Sorry, unexpected error. Please try again later';
//else if GET was used, return the boolean value so that
//ajax script can react accordingly
//1 means success, 0 means failed
} else {
echo $result;
}
//if the errors array has values
} else {
//display the errors message
for ($i=0; $i<count($errors); $i++) echo $errors[$i] . '<br />';
exit;
}
//Simple mail function with HTML header
function sendmail($to, $subject, $email_body, $from) {
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
$headers .= 'From: ' . $from . "\r\n";
$result = mail($to,$subject,$email_body,$headers);
if ($result) return 1;
else return 0;
}
?>
Hosts can vary on their requirements for sendmail and depending on what sendmail software they are using. You may take this up with your hosting company and see if there are any caveats to making it work or if they know a better format.
Use this:
$mailFrom = '"My Name" <info#mydomain.com>';
the FROM label is double quoted and a space and <email>
I edited my initial question to explain how I overcame the problem.