I have built a contact form on a website which is handled by swiftmailer. At the moment it sends correctly with an image attachment and some input fields. How do i make some of the fields "required" and output an error message on those if left empty? Is this something that needs to happen before the swiftmailer library comes into it?
Apologies if this is simple stuff but im new to PHP and cant find a quick answer to this anywhere
<?php
$_SESSION["post"] = $_POST;
$name = $_POST["Name"]; $email = $_POST["Email"]; $phone = $_POST["Phone"]; $dob = $_POST['DOBDay'] ."\t" .$_POST['DOBMonth'] ."\t" .$_POST['DOBYear'];$address = $_POST['AddressLine1'] ."\n" .$_POST['AddressLine2'] ."\n" .$_POST['PostCode'];$experience = $_POST["Experience"];$height = $_POST["Height"]; $size = $_POST["DressSize"];$bra = $_POST["Bra"];$waist = $_POST["Waist"];$hipwidest = $_POST["HipWidest"];$bicep = $_POST["Bicep"];$thigh = $_POST["Thigh"];$shoe = $_POST["Shoe"];
require_once 'lib/swift_required.php';
// Create the Transport
$transport = Swift_SmtpTransport::newInstance('smtp.gmail.com', 465, "ssl")
->setUsername('xxx#gmail.com')
->setPassword('xxx');
// Create the Mailer using your created Transport
$mailer = Swift_Mailer::newInstance($transport);
// Create a message
$message = Swift_Message::newInstance('Be A Model application: Girls')
// Set the From address with an associative array
->setFrom(array($email => $name))
// Set the To addresses with an associative array
->setTo(array('xxx#xxx.com', 'xxx#xxx.com' => 'contact test'))
// Give it a body
->setBody('Name: ' .$name ."\n"
.'Email: ' .$email ."\n"
.'Phone: ' .$phone ."\n"
.'Address: ' .$address ."\n"
.'DOB: ' .$dob ."\n"
.'Experience: ' .$experience ."\n"
.'Height: ' .$height ."\n"
.'Dress Size: ' .$size ."\n"
.'Bra: ' .$bra ."\n"
.'Waist: ' .$waist ."\n"
.'Hip at Widest: ' .$hipwidest ."\n"
.'Bicep: ' .$bicep ."\n"
.'Thigh: ' .$thigh ."\n"
.'Shoe Size: ' .$shoe ."\n" );
// And optionally an alternative body
//->addPart('<q>Here is the message itself</q>', 'text/html');
// Attachment
$message->attach(
Swift_Attachment::fromPath($_FILES['fileatt']['tmp_name'])->setFilename($_FILES['fileatt']['name'])
);
// Send the message
$result = $mailer->send($message);
if ($result)
{
header('Location: http://www.modelmeasures.co.uk/thankyou.html');
}
echo $result;
?>
There are two types of data validation for websites, Client Side and Server Side.
Client Side Validation - This type of validation is typically done using javascript, often as you complete the form. You've seen this on sites that show a 'X', or turn the field colour red, beside an invalid form field BEFORE you even submit it.
Client side validation is useful because it lets the user know that there is a problem before they even submit the form, giving them a chance to correct it.
Server Side Validation - This is where you check the form values when received by the server to make sure it is in the format you expect, doesn't contain invalid information, etc. You see this validation in use when you complete a form, submit it, and the page reloads and tells you there are errors.
You should be doing this type of validation regardless if you validate on the client side or not. It is easy to disable javascript, and if you are only using client side validation people could enter anything they want. This is a security risk.
What I usually do is set my pages up, and use server side validation. This ensures that there are no security issues, and that I am checking the data the user enters. Once that is working I also add client side javascript validation, to make the form more user-friendly. Doing it this way the javascript validation makes sure that the user is entering the correct information, but if something goes wrong, or javascript is disabled, my server validates the data anyways.
So, to answer your question, you really should be doing server side validation at the very least. It would be important to have the validation occur before Swiftmailer actually sends the email, so that emails are not send if invalid data has been entered.
Related
My apologies, I am very new and had difficulty with the editing process etc. I hope the following is more acceptable. The PHP application attaches to the 'receiving email box' and processes the received emails accordingly. It creates a new email that contains comments, attaches the original email and then sends the newly created email back to the 'from address' extracted from the original email. The original email may have been sent from any number of email programs available to users. It may also have pdf/text attachments. When I send the 'newly' created email to Gmail, it displays the attached original email (and it's attachments if any) correctly but not when it is sent to MS Outlook or Horde.
After execturing a new phpmailer class, I added the following:
$mail->CharSet = 'UTF-8';
$mail->Encoding = 'base64';
Coding to save the original email:
$mime = imap_fetchbody($inbox, $email_number, "");
file_put_contents('./workfolder/OriginalEmail.eml', $mime);
I have also tried this coding when saving the original email:
$headers = imap_fetchheader($inbox,$email_number, FT_PREFETCHTEXT);
$body = imap_body($inbox, $email_number);
$structures = imap_fetchstructure($inbox, $email_number);
file_put_contents('./workfolder/OriginalEmail.eml', $headers . '\n' . $body . '\n' . $structures);
I have checked the mime type which displays: message/rfc822
Coding used to attach original email:
$mail->AddAttachment('./workfolder/OriginalEmail.eml');
I have also tried this when attaching the original email:
$mailer->AddAttachment('./workfolder/','OriginalEmail.eml','base64','message/rfc822');
Wednesday - I am having such problems with adding comments.
Here is what I tried:
$strOrigEmail = file_get_contents('./workfolder/OriginalEmail.eml');
echo '<BR><BR>$strOrigEmail: ' . $strOrigEmail;
$mail->addStringAttachment('$strOrigEmail', 'YourEmail.eml');
And the echo displays everything from the original email- headers, body etc. and the attachments (including their filename) but it is endocded. Below is a snippet below of what it looks like:
name=junk.txt Content-Disposition: attachment; size=11; filename=junk.txt junk file --=_7-AofrqAv83eu5i63j73DWn--
I have also tried this and no better - displays same thing as above:
$strOrigEmail = file_get_contents('./workfolder/OriginalEmail.eml');
echo '<BR><BR>$strOrigEmail: ' . $strOrigEmail;
$mail->addStringAttachment(base64_decode('$strOrigEmail'), 'YourEmail.eml');
I am trying to troubleshoot this form. It is not sending reservation requests from the form on the website. Despite showing a message that the form was sent.
I tried editing email and the headers.
<?
//print_r($_POST);
$to = “email#emaildomain.com, {$posting['email']}";
function msg($text){
echo "
<script type='text/javascript'>
alert('".$text."');
top.location.href = 'http://www.aribbq.com';
</script>
";
exit;
}
function error($text){
echo "
<script type='text/javascript'>
alert('".$text."');
history.go(-1);
</script>
";
exit;
}
if (!$_POST[date]) {error('Please, insert Date.');}
if (!$_POST[time]) {error('Please, insert Time.');}
if (!$_POST[party]) {error('Please, insert Party.');}
if (!$_POST[reservation_name]) {error('Please, insert Name.');}
if (!$_POST[reservation_email]) {error('Please, insert Email.');}
if (!$_POST[reservation_phone]) {error('Please, insert Phone.');}
if(isset($_POST['submit'])){
// then send the form to your email
//$from = ('Reservation from AriBBQ.com'); // sender
$mailheaders = "From: contact#aribbq.com" . "\r\n"; // . "CC:
design#youremail.com"
$mailheaders .= 'Reply-To: ' . $posting['Email'] . "\r\n";
$subject = "AriBBQ.com Online Reservation";
$body = "\n Contact Name: ".$_POST[reservation_name]." \r\n\n";
//
$body .= " Email: ".$_POST[reservation_email]." \r\n\n"; //
$body .= " =================================================== \r\n\n"; //
$body .= " Book a table \r\n\n
Date: ".$_POST[date]." \r\n\n
Time: ".$_POST[time]." \r\n\n
Party: ".$_POST[party]." \r\n\n
Contact Details \r\n\n
Name: ".$_POST[reservation_name]." \r\n\n
Email: ".$_POST[reservation_email]." \r\n\n
Phone: ".$_POST[reservation_phone]." \r\n\n
Message: ".$_POST[reservation_message]." \r\n\n"; //
$body .= " =================================================== \r\n\n"; //
$result = mail($to , $from , $subject , $body , $mailheaders);
if($result) {msg('Thank you, your reservation has been sent. We
will send you a confirmation text or call in person.');} //
else{error('Sending mail is failed. Please try again');} //
} else {
error('No submitted. Please try again');
}
?>
You see the form online at http://aribbq.com/. Click on reservations. Once the email is received, we want to be able to reply to the sender's email address.
Alright, essentially, you need to turn on error reporting because your script threw about 20 errors at me which you would see with error reporting on. As my comment above said, add error_reporting(E_ALL); to the top of your script while you debug.
The issues I came across are as follows:
Parse error: syntax error, unexpected '#' in /mail.php on line 4 caused by an incorrect double quote character, not " but “. Subtle, but problematic.
Next up, Multiple or malformed newlines found in additional_header in /mail.php because as of PHP 5.5.2, a bug was fixed to prevent mail header injection, so all of your \n\n within the $mailheaders should be removed, I recommend appending PHP_EOL to the end of each line instead.
You have your $from variable included in the mail() call, this presents 2 issues. One, the mail() function does not have a from parameter, you include it within the headers. Two - your variable is actually commented out.
As I mentioned in the comment above, again, your email address variable to send to is typed as $posting['email']', and $posting['Email'] within $mailheaders. The problem here is $posting doesn't exist. Secondly, your form, which you should include the HTML for in future questions for self-contained examples for people to more easily help you (see https://stackoverflow.com/help/how-to-ask), doesn't post email at all, it posts reservation_email.
Finally, the majority of your $_POST references do not include quotes so PHP doesn't know what to do with the words in between the square brackets. $_POST[date] should be $_POST['date'], for example.
I've made all the above changes and managed to successfully email myself with the script and email form provided, the only thing that I didn't look at was your msg() which didn't show me a success message. I did, however, put an echo statement before this function call which printed out fine.
I hope this helps you get your script up and running, good luck and remember, error_reporting(); is your friend!
I hope I'm missing something pretty basic here but: An empty form is getting submitted randomly, sometimes 3-8 times a day, then none for a few days and so on.
The empty submits always email with the subject as "[Website Contact Form]." Even though there is no validation in my php, in the html code the subject is chosen from a drop-down menu with the default as "General Enquiry." Notice in the php code below, there is no way for a human to submit an empty form with the above subject line, that is, it would always be "[Website Contact Form]General Enquiry" if I press submit without entering anything.
I have contact.html call this contact.php file:
<?
$email = 'info#mail.com';
$mailadd = $_POST['email'];
$headers = 'From: ' . $_POST['email'] . "\r\n";
$name = $_POST['name'];
$subject = '[Website Contact Form] ' . $_POST['subject'];
$message = 'Message sent from: ' . $name . '. Email: ' . $mailadd . '. Organization: ' . $_POST['company'] . '. Phone: ' . $_POST['phone'] . '. ';
$message .= 'Message: ';
$message .= $_POST['message'];
if (mail($email,$subject,$message, $headers)) {
echo "<p>Thank You! We'll get back to you shortly.</p>";
}
else {
echo "<p>Error...</p>";
}
?>
I use this code for many websites, but have never encountered this issue. Is there something so obviously wrong with this code that I'm missing? Any help would be greatly appreciated!
I suspect that you may not be checking that these variables are set before you send the email. Someone requesting contact.php directly (without any form data) may produce the results you have described. If this is the case, the following code should work like a charm:
<?php
if (isset($_POST['submit']) {
// form code
}
else {
// The form was not submitted, do nothing
}
?>
Even if that's not that case, such a simple check is always good practice.
Furthermore, you should always validate any user input just as a good habit. You don't want your server flooding your inbox with emails. I suggest using regexs to validate the input provided and possibly use a captcha service (such as ReCaptcha).
If you've been using this code and it's been working fine then I'd check what variables you changed with this case for example your submit form.
Try out your form with all common possibilities and see if it works. And empty Subject will give your form the subject "[Website Contact Form]". Check that your script actually get's the post variables and your form submits the right variables. Your dropdown might have an option with value of "" and the innerHTML "General Enquiry". The value is what will get submitted.
It's good to check inputs server-side as well
<?php
if(isset($_POST['subject'],$_POST['email'])){
}
?>
A client recently got a spam warning from their host.
I think I have pin pointed the issue to an old contact us form. Simple html on the front end and a simple PHP script on the back end.
if ($_POST['submit'] == "Send"){
//START SEND MAIL SCRIPT
$mail = $_POST['email'];
$to = "me#gmail.com";
$subject = "Message from Website Contact Us Form";
$headers = "From: Contact us Form <webmaster#website.co.uk>";
$message = "Message from Contact Us Form\n\n";
$message .= "\nName: " . $_POST['contactname'];
$message .= "\nEmail: " . $_POST['contactemail'];
$message .= "\nTelephone: " . $_POST['contactphone'];
$message .= "\n\n\nMessage:\n" . $_POST['contactmessage'];
if(mail($to,$subject,$message,$headers)) {
header('Location: http://www.website.co.uk/contact-us/?action=success');
}else{
header('Location: http://www.webisite.co.uk/contact-us/?action=fail');
}//END IF MAIL
}//END SCRIPT
I know the remedies to fix it such as sanitizing post vars properly, using captchas, using a hidden 'honeypot' blank field, js tricks etc etc (I also like the look of this script too http://www.alt-php-faq.com/local/115/)
But to help me understand what was going on I want to know how this script is being manipulated. A foreign script posting vars to it but how do they send email to anyone apart from
'me#gmail.com' or if they are forcing cc / bcc fields somehow why do I not get all spam as well??
Thanks
Line like this $message .= "\nName: " . $_POST['contactname']; can be dangerous.
If $_POST['contactname']='MegaSteve4 \r\nCc: email1#mail.com, email2#mail.com'; are set, 2 uses will get spam mail.
See carefully. Its appending more headers. In this case Cc. I am not sure if Cc is a raw email header. But I hope you get the idea.
You're not doing any escaping of the post data. That means that this form is vulnerable to injection attacks.
I couldn't tell you how they did it, but that's probably what happened.
I have a simple PHP mailer script that takes values from a form submitted via POST and mails them to me:
<?php
$to = "me#example.com";
$name = $_POST['name'];
$message = $_POST['message'];
$email = $_POST['email'];
$body = "Person $name submitted a message: $message";
$subject = "A message has been submitted";
$headers = 'From: ' . $email;
mail($to, $subject, $body, $headers);
header("Location: http://example.com/thanks");
?>
How can I sanitize the input?
Sanitize the post variable with filter_var().
Example here. Like:
echo filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
Since you're not building an SQL query or anything here, the only relevant validation that I can see for those inputs is an email validation for $_POST["email"], and maybe an alphanumeric filter on the other fields if you really want to limit the scope of what the message can contain.
To filter the email address, simply use filter_var:
$email = filter_var($email, FILTER_SANITIZE_EMAIL);
As per Frank Farmer's suggestion, you can also filter out newlines in the email subject:
$subject = str_replace(array("\r","\n"),array(" "," "),$subject);
As others have noted, filter_var is great. If it's not available, add this to your toolchest.
The $headers variable is particularly bad security-wise. It can be appended to and cause spoofed headers to be added. This post called Email Injection discusses it pretty well.
filter_var is great, but another way to assure that something is an email address and not something bad is to use an isMail() function. Here's one:
function isEmail($email) {
return preg_match('|^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]{2,})+$|i', $email);
};
So to use this, you could do:
if (isset($_POST['email']) && isEmail($_POST['email'])) {
$email = $_POST['email'] ;
} else {
// you could halt execution here, set $email to a default email address
// display an error, redirect, or some combination here,
}
In terms of manual validation, limiting the length using substr(), running strip_tags() and otherwise limiting what can be put in.
You need to remove any newlines from input provided by users in $headers, which gets passed to mail() ($email in your case)! See Email injection.
PHP should take care of sanitizing $to and $subject, but there are versions of PHP with bugs (Affected are PHP 4 <= 4.4.6 and PHP 5 <= 5.2.1, see MOPB-34-2007).
You can use the code from artlung's answer above to validate email..
I use this kind of code to prevent header injection ..
// define some mail() header's parts and commonly used spam code to filter using preg_match
$match = "/(from\:|to\:|bcc\:|cc\:|content\-type\:|mime\-version\:|subject\:|x\-mailer\:|reply\-to\:|\%0a|\%0b)/i";
// check if any field's value containing the one or more of the code above
if (preg_match($match, $name) || preg_match( $match, $message) || preg_match( $match, $email)) {
// I use ajax, so I call the string below and send it to js file to check whether the email is failed to send or not
echo "failed";
// If you are not using ajax, then you can redirect it with php header function i.e: header("Location: http://example.com/anypage/");
// stop the script before it reach or executing the mail function
die();
}
The mail()'s header filtering above is too strict, since some users may be using the filtered strings in their message without any intention to hijack your email form, so redirect it to a page that is explaining what kind of strings that is not allowed in the form or explain it on your form page.