I'm trying to implement a contact form using PHPMailer but I can't make the attachment from the upload field to be sent. The contact form do work and all the other fields are sent.
I followed this tutorial with no luck.
Also tried numerous different PHP scripts such as this, this and this one, among others.
The current code I have that seems to be the most successfully used is this one:
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
require_once 'phpmailer/PHPMailerAutoload.php';
// Attack #1 preventor - Spam Honeypot
if ($_POST["address"] != "") {
echo "SPAM HONEYPOT";
exit;
}
// Attack #2 preventor - Email header injection hack preventor
foreach($_POST as $value) {
if(stripos($value, 'Content-Type:') !== FALSE) {
echo "There was a problem with the information you entered.";
exit;
}
}
if (isset($_POST['inputNome']) && isset($_POST['inputEmail']) && isset($_POST['inputMensagem'])) {
//check if any of the inputs are empty
if (empty($_POST['inputNome']) || empty($_POST['inputEmail']) || empty($_POST['inputMensagem'])) {
$data = array('success' => false, 'message' => 'Preencha todos os campos requeridos.');
echo ($data);
exit;
}
//create an instance of PHPMailer
$mail = new PHPMailer();
// Set up SMTP
$mail->IsSMTP(); // Sets up a SMTP connection
$mail->SMTPAuth = true; // Connection with the SMTP does require authorization
$mail->SMTPSecure = "ssl"; // Connect using a TLS connection
$mail->Host = "************"; //Gmail SMTP server address
$mail->Port = 465; //Gmail SMTP port
$mail->Encoding = '7bit';
// Authentication
$mail->Username = "*************"; // Your full Gmail address
$mail->Password = "*********"; // Your Gmail password
$mail->CharSet = 'UTF-8';
// Compose
$mail->SetFrom($_POST['inputEmail'], $_POST['inputNome']);
$mail->AddReplyTo($_POST['inputEmail'], $_POST['inputNome']);
$mail->Subject = "My Company - " . $_POST['inputAssunto']; // Subject (which isn't required)
$mail->AddAddress('name#myemail.com'); //recipient
//Add attachment
$mail->addAttachment($_FILES['inputBriefing']);
if (isset($_FILES['inputBriefing']) &&
$_FILES['inputBriefing']['error'] == UPLOAD_ERR_OK) {
$mail->addAddress($_FILES['inputBriefing']['tmp_name'],
$_FILES['inputBriefing']['name']);
}
$mail->Body = "Nome: " . $_POST['inputNome'] . "\r\nEmail: " . $_POST['inputEmail'] . "\r\nTelefone: " .$_POST['inputTelefone'] . "\r\nAssunto: " . $_POST['inputAssunto'] . "\r\nMensagem: " . stripslashes($_POST['inputMensagem']);
if(!$mail->send())
{
echo 'An error has occurred.';
exit;
}
echo 'Message successfully sent';
}
?>
And the form:
<form id="contact" method="post" action="<?php echo get_template_directory_uri(); ?>/form-contact.php">
<div class="form-group">
<label for="inputNome">Nome Completo *</label>
<input type="text" id="inputNome" name="inputNome" required class="form-control" placeholder="Nome Completo">
</div>
<div class="form-group">
<label for="inputEmail">E-mail *</label>
<input type="email" id="inputEmail" name="inputEmail" required class="form-control" placeholder="Digite seu e-mail">
</div>
<div class="form-group">
<label for="inputTelefone">Telefone</label>
<input type="tel" id="inputTelefone" name="inputTelefone" class="form-control" placeholder="Telefone">
</div>
<div class="form-group">
<label for="inputAssunto">Assunto</label>
<select class="form-control" id="inputAssunto" name="inputAssunto" >
<option disabled selected value> -- Selecione -- </option>
<option value="Orçamento">Orçamento</option>
<option value="Hospedagem">Hospedagem</option>
<option value="Dúvidas">Dúvidas</option>
<option value="Informações">Informações</option>
<option value="Outro">Outro</option>
</select>
</div>
<div class="form-group">
<label for="inputBriefing">Briefing</label>
<input type="hidden" name="MAX_FILE_SIZE" value="30000" />
<input type="file" id="inputBriefing" name="inputBriefing">
<p class="help-block">Se preferir adicione seus arquivos (.pdf, .docx ou .zip)</p>
</div>
<!--Hpam Sponypot -->
<div class="form-group" style="visibility: hidden">
<label for="address">Address</label>
<input type="text" name="address" id ="address">
<p> Humans, do not fill out this form! </p>
</div>
<div class="form-group">
<label for="inputMensagem">Mensagem *</label>
<textarea class="form-control" rows="3" id="inputMensagem" name="inputMensagem" required placeholder="Escreva sua mensagem"></textarea>
</div>
<p><small>* Campos obrigatórios.</small></p>
<button type="submit" class="btn btn-info">Enviar</button>
</form>
I'm using a shared host on Hostgator.
You were attempting to add the file as a new destination address and not an attachment.
See below for suggested amendment.
//Add attachment
// $_FILES['inputBriefing'] is an array not the file
// adding the file as an attachment before checking for errors is a bad idea also
//$mail->addAttachment($_FILES['inputBriefing']);
if (isset($_FILES['inputBriefing']) && $_FILES['inputBriefing']['error'] == UPLOAD_ERR_OK) {
// this is attempting to add an address to send the email to
//$mail->addAddress($_FILES['inputBriefing']['tmp_name'],$_FILES['inputBriefing']['name']);
$mail->addAttachment($_FILES['inputBriefing']['tmp_name'],
$_FILES['inputBriefing']['name']);
}
You have to add enctype in you form tag like this.
<form id="contact" method="post" action="<?php echo get_template_directory_uri(); ?>/form-contact.php" enctype="multipart/form-data">
Try this form tag
Related
I've recently started working with PHPMailer to email my contactforms and after some puzzling, it works great. The only 'downside' is that the user gets redirected after sending an email. For example:
If one would fill in the form here, they will be redirected to another page like this one when the message sent succesfully.
My HTML for my form is the following:
<form class="form ajax-contact-form" method="post" action="php/contact.php">
<div class="alert alert-success hidden" id="contact-success">
<strong>Votre message a été envoyé avec
succès!</strong> Merci, nous contacterons vous dès que possible.
</div>
<div class="alert alert-danger hidden" id="contact-error">
<strong>Votre message n'a pas été envoyé.</strong> Vous
avez tout rempli correctement?
</div>
<div class="row col-p10">
<div class="col-sm-6">
<label class="mb10"><input type="text" name="name_" id="name_" required="" class=
"form-control" placeholder="Votre nom" /></label>
</div>
<div class="col-sm-6">
<label class="mb10"><input type="text" name="adress_" id="subject_" required=""
class="form-control" placeholder="Votre adresse" /></label>
</div>
</div>
<div class="row col-p10">
<div class="col-sm-6">
<label class="mb10"><input type="number" name="zipcode_" id="zipcode_" required=
"" class="form-control" placeholder="Code postal" /></label>
</div>
<div class="col-sm-6">
<label class="mb10"><input type="text" name="city_" id="city_" required="" class=
"form-control" placeholder="Ville ou commune" /></label>
</div>
</div>
<div class="row col-p10">
<div class="col-sm-6">
<label class="mb10"><input type="tel" name="phone_" id="phone_" required=""
class="form-control" placeholder=
"Votre numéro de téléphone" /></label>
</div>
<div class="col-sm-6">
<label class="mb10"><input type="email" name="email_" id="email_" required=""
class="form-control" placeholder="Votre adresse d'email" /></label>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<label><select name="select_" id="select_" required="" class="form-control">
<option value="Invalid">
Choisi un option
</option>
<option value="CV Ketel huren">
Je veux louer une chaudière
</option>
<option value="CV Ketel kopen">
Je veux acheter une chaudière
</option>
<option value="Ik wens meer informatie">
Je veux plus d'infos
</option>
</select></label>
</div>
</div><label>
<textarea name="message_" id="message_" cols="30" rows="10" class="form-control"
placeholder="Votre message (optionel)">
</textarea></label>
<div class="mb40"></div>
<div class="clearfix">
<div class="pull-left">
<button type="submit" class="btn btn-icon btn-e">Envoi</button>
</div>
</div>
</form>
The php for my form is the following:
<?php
session_cache_limiter('nocache');
header('Expires: ' . gmdate('r', 0));
header('Content-type: application/json');
// Include PHPMailer class
include("./PHPMailer/PHPMailerAutoload.php");
// grab reCaptcha library
require_once "./reCaptcha/recaptchalib.php";
///////////////////////////////////////////////////////////////////////
// Enter your email address below.
$to_address = "info#cvketelshuren.com";
// Enter your secret key (google captcha)
$secret = "Leftout for apparent reasons";
//////////////////////////////////////////////////////////////////////
// Verify if data has been entered
if(!empty($_POST['name_']) || !empty($_POST['adress_']) || !empty($_POST['zipcode_']) || !empty($_POST['city_']) || !empty($_POST['phone_']) || !empty($_POST['email_']) || !empty($_POST['select_'])) {
$name = $_POST['name_'];
$adress = $_POST['adress_'];
$zipcode = $_POST['zipcode_'];
$city = $_POST['city_'];
$phone = $_POST['phone_'];
$email = $_POST['email_'];
$select = $_POST['select_'];
// Configure the fields list that you want to receive on the email.
$fields = array(
0 => array(
'text' => 'Naam',
'val' => $_POST['name_']
),
1 => array(
'text' => 'Adres',
'val' => $_POST['adress_']
),
2 => array(
'text' => 'Stad',
'val' => $_POST['zipcode_']." ".$_POST['city_']
),
3 => array(
'text' => 'Select',
'val' => $_POST['select_']
),
4 => array(
'text' => 'Telefoonnummer',
'val' => $_POST['phone_']
),
5 => array(
'text' => 'Mailadres',
'val' => $_POST['email_']
),
6 => array(
'text' => 'Bericht',
'val' => $_POST['message_']
)
);
$message = "Waarde collega,<br>Er werd een contactformulier ingevuld op de site cvketelshuren.com<br>Gelieve hieronder de gegevens van de klant terug te vinden.<br>";
foreach($fields as $field) {
$message .= $field['text'].": " . htmlspecialchars($field['val'], ENT_QUOTES) . "<br>\n";
}
$mail = new PHPMailer;
$mail->IsSMTP(); // Set mailer to use SMTP
$mail->SMTPDebug = 0; // Debug Mode
// If you don't receive the email, try to configure the parameters below:
$mail = new PHPMailer;
$mail->Host = 'mailout.one.com';
$mail->SMTPAuth = true;
$mail->Username = '***************';
$mail->Password = '************';
$mail->SMTPSecure = false;
$mail->Port = 25;
$mail->From = $email;
$mail->FromName = $name;
$mail->AddAddress($to_address);
$mail->AddReplyTo($email, $name);
if (!empty($_POST['send_copy_'])) {
$mail->AddAddress($email);
}
$mail->IsHTML(true); // Set email format to HTML
$mail->CharSet = 'UTF-8';
$mail->Subject = 'Vraag via CV Ketels Huren [NL]';
$mail->Body = $message;
// Google CAPTCHA
$resp = null; // empty response
$reCaptcha = new ReCaptcha($secret); // check secret key
// if submitted check response
if ($_POST["g-recaptcha-response"]) {
$resp = $reCaptcha->verifyResponse(
$_SERVER["REMOTE_ADDR"],
$_POST["g-recaptcha-response"]
);
}
// if captcha is ok, send email
if ($resp != null && $resp->success) {
if($mail->Send()) {
$result = array ('response'=>'success');
} else {
$result = array ('response'=>'error' , 'error_message'=> $mail->ErrorInfo);
}
} else {
$result = array ('response'=>'error' , 'error_message'=>'Google ReCaptcha did not work');
}
echo json_encode($result);
} else {
$result = array ('response'=>'error' , 'error_message'=>'Data has not been entered');
echo json_encode($result);
}
?>
As you can see, an error and success message was already coded in but if redirecting is something that should happen, I want to code a custom HTML-page. Anybody that can help me set the redirect so I can start coding?
Thanks for your time!
You are not doing any redirects here. Your form tag contains action="php/contact.php", so that's where the form will submit to. If you want to go somewhere else after processing the form submission and sending a message, you can do a redirect like this:
header('Location: some_other_url/page.php');
If the form contains errors, you could redirect back to the form, passing error messages in the URL parameters.
I have an html from. When the user submits the form, I'm sending an email to the given email address using php. Emails to gmail accounts go through perfectly fine. However, mails to providers like yahoo, aol etc does not go through.There is no filter mechanism in my code to filter out email addresses. Some mails to yahoo mail addresses goes through rarely. But aol doesn't go at all. What is the issue here?
My html code:
<section class="contact-container">
<div class="container mtb">
<div class="row">
<div class="col-md-8 wow fadeInLeft">
<h4>Get in touch</h4>
<hr>
<p>Leave a comment, review, or general musings.
</p><br/>
<form method="post" id="captcha_form" name=
"captcha_form" action="mailform.php"><fieldset><ol>
</li><li><label class="solo" for="email">Email address:</label>
<span class="required">(required)</span><input type="text" class="solo
input" name="email" id="email" value="" />
</li><li><label class="solo" for="name">Name:</label><input type=
"text" class="solo input" name="name" id="name" value="" />
</li><li><label class="solo" for="subject">Subject:</label>
<span class="required">(required)</span> <input type="text" class=
"solo input" name="subject" id="subject" />
</li><li><label class="solo" for="message">Message:</label>
<span class="required">(required)</span>
<div class="solo input"><textarea class="solo input" name="message" id=
"message" ></textarea><br />
<p><input name="submit" id="submit" type="submit" value="Send" style=
"float: right;" /></p></div>
</li></ol>
</fieldset></form> <br /> <br />
</div>
And here is snippets of mailform.php:
<?php
$dontsendemail = 0;
$possiblespam = FALSE;
$strlenmessage = "";
$email = $_REQUEST['email'];
$message = $_REQUEST['message'];
$subject = $_REQUEST['subject'];
$emailaddress = "email#gmail.com";
/ Check human test input box
if(isset($_REQUEST["htest"]) && $_REQUEST["htest"] != "") die
("Possible spam detected. Please hit your browser back button
and check your entries.");
// Check email address function
function checkemail($field) {
// checks proper syntax
if( !preg_match( "/^([a-zA-Z0-9])+([a-zA-Z0-9._-])*#([a-zA-Z0-9_-])+
([a-zA-Z0- 9._-]+)+$/", $field))
{
die("Improper email address detected. Please hit your browser back
button and enter a proper email address.");
return 1;
}
}
// Spamcheck function
function spamcheck($field) {
if(preg_match("/to:/i",$field) || preg_match("/cc:/i",$field)
|| preg_match("/\r/i",$field) || preg_match("/i\n/i",$field)
|| preg_match("/%0A/i",$field)){
$possiblespam = TRUE;
}else $possiblespam = FALSE;
if ($possiblespam) {
die("Possible spam attempt detected. If this is not the case, please
editthe content of the contact form and try again.");
return 1;
}
}
if ($dontsendemail == 0) {
$message="";
$message.="Name: ".$name."\r\n";
$message.="Mailing Address: \r\nLine 1: ".$addressline1."\r\nLine
2: ".$addressline2."\r\nCity: ".$city."\r\nState: ".$state."
\r\nZip: ".$zip."\r\n";
$message=$message."\r\nMessage:\r\n".$_REQUEST['message'];
mail($emailaddress,"$subject",$message,"From: $email" );
include "email_sent.php";
echo "Thank you, I will respond shortly.";
}
Don't use a regex to confirm email addresses. The real regex is like a day long. Use http://www.w3schools.com/php/filter_validate_email.asp or https://code.google.com/p/php-smtp-email-validation/ or https://github.com/appskitchen/emailverifier/blob/master/class.emailverify.php . You'll notice they are much more complicated than a basic regex. The email spec is insane: https://www.rfc-editor.org/rfc/rfc2822
Fist time using the GitHub PHPMailer and I have an issue with sending emails.
The data seems to be sent to the form and I am lost beyond that.
I know I am not using the errors in my page, which is why for now I am printing them to the php form.
html (index.php)
<form name="contactform" id="myform" class="fs-form fs-form-full" autocomplete="off" method="post" action="send.php">
<ol class="fs-fields">
<li>
<label class="fs-field-label fs-anim-upper" for="q1">What's your name?</label>
<input class="fs-anim-lower" id="q1" name="q1" type="text" placeholder="Johnny Bravo" required/>
</li>
<li>
<label class="fs-field-label fs-anim-upper" for="q2" data-info="We won't send you spam, we promise...">What's your email address?</label>
<input class="fs-anim-lower" id="q2" name="q2" type="email" placeholder="me#email.com" required/>
</li>
<li data-input-trigger>
<label class="fs-field-label fs-anim-upper" for="q3" data-info="This will help us know what kind of service you need">What can we do for you? <span style="font-size:20px;">(select one)</span></label>
<div class="fs-radio-group fs-radio-custom clearfix fs-anim-lower">
<span><input id="q3b" name="q3" type="radio" value="graphic"/><label for="q3b" class="radio-graphic">Graphic Design</label></span>
<span><input id="q3c" name="q3" type="radio" value="web"/><label for="q3c" class="radio-web">Web Design</label></span>
<span><input id="q3a" name="q3" type="radio" value="motion"/><label for="q3a" class="radio-motion">Motion Graphics</label></span>
<span><input id="q3d" name="q3" type="radio" value="other"/><label for="q3d" class="radio-other">Other/More</label></span>
</div>
</li>
<li>
<label class="fs-field-label fs-anim-upper" for="q4">Describe your project in detail.</label>
<textarea class="fs-anim-lower" id="q4" name="q4" placeholder="Describe here"></textarea>
</li>
<li>
<label class="fs-field-label fs-anim-upper" for="q5">What's your budget? (USD)</label>
<input class="fs-mark fs-anim-lower" id="q5" name="q5" type="number" placeholder="1000" step="100" min="100"/>
</li>
</ol><!-- /fs-fields -->
<button class="fs-submit" type="submit" value="Send">Send It</button>
</form><!-- /fs-form -->
PHP (send.php)
<?php
session_start();
require_once 'libs/phpmailer/PHPMailerAutoload.php';
$errors = [];
if(isset($_POST['q1'], $_POST['q2'], $_POST['message'])) {
$fields = [
'q1' => $_POST['q1'],
'q2' => $_POST['q2'],
'q3' => $_POST['q3'],
'q4' => $_POST['q4'],
'q5' => $_POST['q5']
];
foreach($fields as $field => $data) {
if(empty($data)) {
$errors[] = 'The ' . $field . ' field is required.';
}
}
if(empty($errors)) {
$m = new PHPMailer;
$m->isSMTP();
$m->SMTPAuth = true;
$m->Host = 'smtp.gmail.com';
$m->Username = 'myemail#gmail.com';
$m->Password = 'mypassword';
$m->SMTPSecure = 'ssl';
$m->Port = 465;
$m->isHTML();
$m->Subject = 'Contact form submitted';
$m->Body = 'From: ' . $fields['q1'] . ' (' . $fields['q2'] . ')<p>Budget</p><p>' . $fields['q5'] . '</p><p>Service</p><p>' . $fields['q3'] . '</p><p>Details</p><p>' . $fields['q4'] . '</p>';
$m->FromName = 'Contact';
$m->AddAddress('myemail#gmail.com', 'Ollie Taylor');
if($m->send()) {
header('Location: thanks.php');
die();
} else {
$errors[] = 'Sorry, could not send email. Try again later.';
}
}
} else {
$errors[] = 'Something went wrong.';
}
$_SESSION['errors'] = $errors;
$_SESSION['fields'] = $fields;
header('Location: index.php');
Thankyou!
You have some syntax errors for starters.
Line 30 of send.php
$m-Host = 'smtp outgoing here';
Should be
$m->Host = 'smtp outgoing here';
and line 39
$m->Body = 'From:: ' . $fields['q1'] . '(' $fields['q2'] ')' . $fields['q3'] . $fields['q4'] . $fields['q5'];
Should be
$m->Body = 'From:: ' . $fields['q1'] . '(' . $fields['q2'] . ')' . $fields['q3'] . $fields['q4'] . $fields['q5'];
(added concatenation inbetween your parenthesis)
Overall, I'd suggest you look into your PHP error log. I haven't tested it further to see if the email actually sends. But big picture here: Check PHP error log.
I'm trying to get my contact form to work but since I don't have and IDE with a debugger I can't figure out where the PHP code fails.
Also, instead of a success message that replaces the message box and submit button which I think it's doing now, I would like to redirect to thank-you.html
Would appreciate some pointers.
HTML
<div class="col-md-6 text-left small-screen-center os-animation" data-os-animation="fadeInRight" data-os-animation-delay="0.3s">
<form id="contactForm" class="contact-form">
<div class="form-group form-icon-group">
<input class="form-control" id="name" name="name" placeholder="Your name *" type="text" required/>
<i class="fa fa-user"></i> </div>
<div class="form-group form-icon-group">
<input class="form-control" id="email" name="email" placeholder="Your email *" type="email" required>
<i class="fa fa-envelope"></i> </div>
<div class="form-group form-icon-group">
<input class="form-control" id="number" name="number" placeholder="Your number " type="number">
<i class="fa fa-phone"></i> </div>
<div class="form-group form-icon-group">
<input class="form-control" id="company" name="company" placeholder="Your company " type="text">
<i class="fa fa-briefcase"></i> </div>
<div class="form-group form-icon-group">
<input class="form-control" id="subject" name="subject" placeholder="Subject " type="text">
<i class="fa fa-briefcase"></i> </div>
<div class="form-group form-icon-group">
<textarea class="form-control" id="message" name="message" placeholder="Your message *" rows="5" required></textarea>
<i class="fa fa-pencil"></i> </div>
<div>
<input type="submit" value="send message" class="btn btn-link">
</div>
</form>
<div id="messages" style="padding-top:10px;"></div>
</div>
PHP
<?php
require 'vendor/phpmailer/phpmailer/PHPMailerAutoload.php';
$mail = new PHPMailer;
// Setting up PHPMailer
$mail->IsSMTP(); // Set mailer to use SMTP
// Visit http://phpmailer.worxware.com/index.php?pg=tip_srvrs for more info on server settings
// For GMail => smtp.gmail.com
// Hotmail => smtp.live.com
// Yahoo => smtp.mail.yahoo.com
// Lycos => smtp.mail.lycos.com
// AOL => smtp.aol.com
$mail->Host = 'secure.emailsrvr.com'; // Specify main and backup server
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->SMTPDebug = 3;
//This is the email that you need to set so PHPMailer will send the email from
$mail->Username = 'my#emailadress.com'; // SMTP username
$mail->Password = 'XXXXXX'; // SMTP password
$mail->SMTPSecure = 'tls';
$mail->Port = 465; // TCP port to connect to
// Add the address to send the mail to
$mail->AddAddress('my#emailadress.com');
$mail->WordWrap = 50; // Set word wrap to 50 characters
$mail->IsHTML(true); // Set email format to HTML
// add your company name here
$company_name = 'My Company';
// choose which fields you would like to be validated separated by |
// options required - check input has content valid_email - check for valid email
$field_rules = array(
'name' => 'required',
'email' => 'required|valid_email',
'message' => 'required'
);
// change your error messages here
$error_messages = array(
'required' => 'This field is required',
'valid_email' => 'Please enter a valid email address'
);
// select where each inputs error messages will be shown
$error_placements = array(
'name' => 'top',
'email' => 'top',
'subject' => 'right',
'message' => 'right',
'submitButton' => 'right'
);
// success message
$success_message = new stdClass();
$success_message->message = 'Thanks! your message has been sent';
$success_message->field = 'submitButton';
$success_message->placement = $error_placements['submitButton'];
// mail failure message
$mail_error_message = new stdClass();
$mail_error_message->message = 'Sorry your mail was not sent - please try again later';
$mail_error_message->field = 'submitButton';
$mail_error_message->placement = $error_placements['submitButton'];
// DONT EDIT BELOW THIS LINE UNLESS YOU KNOW YOUR STUFF!
$fields = $_POST;
$returnVal = new stdClass();
$returnVal->status = 'error';
$returnVal->messages = array();
if (!empty($fields)) {
//Validate each of the fields
foreach ($field_rules as $field => $rules) {
$rules = explode('|', $rules);
foreach ($rules as $rule) {
$result = null;
if (isset($fields[$field])) {
if (!empty($rule)) {
$result = $rule($fields[$field]);
}
if ($result === false) {
$error = new stdClass();
$error->field = $field;
$error->message = $error_messages[$rule];
$error->placement = $error_placements[$field];
$returnVal->messages[] = $error;
// break from the rule loop so we only get 1 error at a time
break;
}
} else {
$returnVal->messages[] = $field . ' ' . $error_messages['required'];
}
}
}
if (empty($returnVal->messages)) { // Enable encryption, 'ssl' also accepted
$email = stripslashes(safe($fields['email']));
$body = stripslashes(safe($fields['message']));
// The sender of the form/mail
$mail->From = $email;
$mail->FromName = stripslashes(safe($fields['name']));
$mail->Subject = '[' . $company_name . ']';
$content = $email . " sent you a message from your contact form:<br><br>";
$content .= "-------<br>" . $body . "<br><br><br><br>Email: " . $email;
$mail->Body = $content;
if(#$mail->Send()) {
$returnVal->messages[] = $success_message;
$returnVal->status = 'ok';
} else {
$returnVal->messages[] = $mail_error_message;
}
}
echo json_encode($returnVal);
}
function required($str, $val = false)
{
if (!is_array($str)) {
$str = trim($str);
return ($str == '') ? false : true;
} else {
return !empty($str);
}
}
function valid_email($str)
{
return (!preg_match("/^(?!(?:(?:\\x22?\\x5C[\\x00-\\x7E]\\x22?)|(?:\\x22?[^\\x5C\\x22]\\x22?)){255,})(?!(?:(?:\\x22?\\x5C[\\x00-\\x7E]\\x22?)|(?:\\x22?[^\\x5C\\x22]\\x22?)){65,}#)(?:(?:[\\x21\\x23-\\x27\\x2A\\x2B\\x2D\\x2F-\\x39\\x3D\\x3F\\x5E-\\x7E]+)|(?:\\x22(?:[\\x01-\\x08\\x0B\\x0C\\x0E-\\x1F\\x21\\x23-\\x5B\\x5D-\\x7F]|(?:\\x5C[\\x00-\\x7F]))*\\x22))(?:\\.(?:(?:[\\x21\\x23-\\x27\\x2A\\x2B\\x2D\\x2F-\\x39\\x3D\\x3F\\x5E-\\x7E]+)|(?:\\x22(?:[\\x01-\\x08\\x0B\\x0C\\x0E-\\x1F\\x21\\x23-\\x5B\\x5D-\\x7F]|(?:\\x5C[\\x00-\\x7F]))*\\x22)))*#(?:(?:(?!.*[^.]{64,})(?:(?:(?:xn--)?[a-z0-9]+(?:-[a-z0-9]+)*\\.){1,126}){1,}(?:(?:[a-z][a-z0-9]*)|(?:(?:xn--)[a-z0-9]+))(?:-[a-z0-9]+)*)|(?:\\[(?:(?:IPv6:(?:(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){7})|(?:(?!(?:.*[a-f0-9][:\\]]){7,})(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,5})?::(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,5})?)))|(?:(?:IPv6:(?:(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){5}:)|(?:(?!(?:.*[a-f0-9]:){5,})(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,3})?::(?:[a-f0-9]{1,4}(?::[a-f0-9]{1,4}){0,3}:)?)))?(?:(?:25[0-5])|(?:2[0-4][0-9])|(?:1[0-9]{2})|(?:[1-9]?[0-9]))(?:\\.(?:(?:25[0-5])|(?:2[0-4][0-9])|(?:1[0-9]{2})|(?:[1-9]?[0-9]))){3}))\\]))$/iD", $str)) ? false : true;
}
function safe($name)
{
return(str_ireplace(array("\r", "\n", '%0a', '%0d', 'Content-Type:', 'bcc:','to:','cc:'), '', $name));
}
Oh, one more thing: This contact form came with a website template and within the contact.js I found this warning:
Usage Note:
-----------
Do not use both ajaxSubmit and ajaxForm on the same form. These
functions are mutually exclusive. Use ajaxSubmit if you want
to bind your own submit handler to the form.
What does that mean exactly? The contact.js contains code for both. Do I need to delete some of it to get it to work?
Here is the jsfiddle for the contact.js
I am stuck in bit of a situation here. So the issue is that I have a simple form which gets the data using $_POST and emails the data to a email (I am using PHPMailer). Now I have to integrate a Paypal button in it so that the client could be redirected to the Paypal page for payment, the issue is that the Paypal button is a form and it has its own action and I am not sure how to apply both (Paypal and Emailing) actions together in the same form. Can someone please guide me here?
Emailing Form:
<form action="process-email.php" class="floatfix" id="card-form" method="post" data-message="Thank you for purchasing. We will contact you via email." enctype="multipart/form-data">
<div class="flt-l left">
<div class="field-container">
<div class="field-number">1</div>
<h3 class="txt-a-c h3-title"><img src="img/icons/clipboard.png" alt="">Place your Order</h3>
<div class="form-panels floatfix clr-b">
<div class="flt-l left-side-panel">
<div id="form-contact-details-container" class="form-contact-details-container">
<input type="text" tabindex="10" required value="Full Name" name="full-name">
<input type="text" tabindex="20" required value="Office #" name="office">
<input type="text" tabindex="30" required value="Mobile #" name="mobile">
<input type="text" tabindex="40" required value="Email" name="email">
<input type="text" tabindex="50" required value="Website" name="website">
</div>
<div class="card-styles floatfix">
Card Style
</div>
<div class="card-shots">
<div class="card-shot pos-r floatfix">
<input type="radio" name="body_shots" id="card-shot-none" data-card-shot-type="none" value="Full Shot" checked class="active">
<span class="radio">No <br>Shot</span>
<img src="img/card_empty.png" alt="" class="card-empty-img">
<div class="check-mark"><img src="img/icons/check_round.png" alt=""></div>
</div>
<div class="card-shot pos-r floatfix">
<input type="radio" name="body_shots" id="card-shot-half" data-card-shot-type="half" value="Half Shot">
<span class="radio">Half Body <br>Shot</span>
<img src="img/card_half_pic.png" alt="">
<div class="check-mark"><img src="img/icons/check_round.png" alt=""></div>
</div>
<div class="card-shot pos-r floatfix">
<input type="radio" name="body_shots" id="card-shot-full" data-card-shot-type="full" value="Full Shot">
<span class="radio">Full Body <br>Shot</span>
<img src="img/card_full_pic.png" alt="">
<div class="check-mark"><img src="img/icons/check_round.png" alt=""></div>
</div>
</div>
<div id="upload-container" class="noselect notify-hover upload-container">
<div class="inner">
<div id="upload-preview" class="page-cover upload-img-container"></div>
<div class="upload-text">Upload Your Photo <span class="camera"></span></div>
<input id="upload-file" class="upload-file" type="file" name="upload-file[]" multiple="multiple">
</div>
<div class="notify">
<h6 class="fnt-w-b">Only Upload files less than 2mb.</h6>
<p>Please allow 2 Business Days for Photo Filtering and Processing.</p>
</div>
</div>
<div class="pos-r notify-hover shipping-address">
<input id="shipping-address-1" type="text" placeholder="Shipping Address" tabindex="60" name="shipping_address_1">
<span id="shipping-address-1-holder" class="pos-a hidden"></span>
<input id="shipping-address-2" type="text" tabindex="70" name="shipping_address_2">
<span id="shipping-address-2-holder" class="pos-a hidden"></span>
<div class="notify">
<p>Carefully Fill this as we do not offer refund on lost packages.</p>
</div>
</div>
</div>
<div class="flt-r right-side-panel">
<span class="noselect crs-p card-flipper">See <span data-before="Back" data-after="Front"></span> of Card</span>
<div class="pos-r">
<div id="the-card" class="noselect card-preview-container">
<div class="card card-front">
<div class="full-before full-after card-pic"></div>
<div id="card-detail-preview-container" class="card-detail-preview noselect crs-d"></div>
</div>
<div class="card card-back"><img src="img/card_back.png" alt=""></div>
</div>
</div>
</div>
</div>
<div class="submit-button-container">
<input type="submit" value="" id="card-form-submit">
<div class="submit-button">
<h2 class="txt-t-u">$125 - Order Now</h2>
<div>1000 Business Cards</div>
</div>
<img src="img/paypal.png" alt="" class="paypal">
<p class="small txt-a-c">You will be takend to Paypal for payment processing</p>
</div>
</div>
</div>
<div class="flt-r right">
<div class="field-container">
<div class="field-number">2</div>
<div class="checkbox-container">
<div class="checkbox">
<img src="img/icons/check.png" alt="">
</div>
<span class="label">Approve & Receive It</span>
</div>
<p class="p-1">You will receive a PDF of the final card with your processed photo.</p>
<p class="p-2">You will receive your order within 7-10 business days.</p>
</div>
</div>
</form>
PayPal Form:
<form action="https://www.paypal.com/cgi-bin/webscr" method="post" target="_top">
<input type="hidden" name="cmd" value="_s-xclick">
<input type="hidden" name="hosted_button_id" value="KJU58">
<input type="image" src="http://www.deadlyfishesmods.com/wp-content/uploads/2013/09/Buy-Now-Button.png" border="0" name="submit" alt="PayPal - The safer, easier way to pay online!">
<img alt="" border="0" src="https://www.paypalobjects.com/en_US/i/scr/pixel.gif" width="1" height="1">
</form>
Process-email.php:
<?php
if(isset($_POST['full-name'])) {
require 'includes/PHPMailerAutoload.php';
require 'includes/config.php';
$smtp_host = $config["SMTP_HOST"];
$email = $config["EMAIL"];
$email_password = $config["EMAIL_PASSWORD"];
$email_subject = $config["EMAIL_SUBJECT"];
$name = $_POST['full-name']; // required
$office = $_POST['office']; // required
$mobile = $_POST['mobile']; // required
$user_email = $_POST['email']; // required
$website = $_POST['website']; // required
$card_type = $_POST['body_shots'];
$address_1 = $_POST['shipping_address_1'];
$address_2 = $_POST['shipping_address_2'];
$email_exp = '/^[A-Za-z0-9._%-]+#[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';
function clean_string($string) {
$bad = array("content-type","bcc:","to:","cc:","href");
return str_replace($bad,"",$string);
}
$email_message = "You have a new card order. <br/> <br/>";
$email_message .= "Name: ".clean_string($name)."<br/>";
$email_message .= "Office: ".clean_string($office)."<br/>";
$email_message .= "Mobile Number: ".clean_string($mobile)."<br/>";
$email_message .= "Email: ".clean_string($user_email)."<br/>";
$email_message .= "Website: ".clean_string($website)."<br/>";
$email_message .= "Card Type: ".clean_string($card_type)."<br/>";
$email_message .= "Address: ".clean_string($address_1) . clean_string($address_2) . "<br/>";
$mail = new PHPMailer(); // create a new object
$mail->IsSMTP(); // enable SMTP
$mail->SMTPDebug = 0; // debugging: 1 = errors and messages, 2 = messages only
$mail->SMTPAuth = true; // authentication enabled
$mail->SMTPSecure = 'ssl'; // secure transfer enabled REQUIRED for GMail
$mail->Host = "$smtp_host";
$mail->Port = 465; // or 587
$mail->IsHTML(true);
$mail->Username = "$email";
$mail->Password = "$email_password";
$mail->Subject = "$email_subject";
$mail->Body = $email_message;
$validAttachments = array();
if($card_type !== "Full Shot"){
foreach($_FILES['upload-file']['name'] as $index => $fileName) {
$filePath = $_FILES['upload-file']['tmp_name'][$index];
$validAttachments[] = array($filePath, $fileName);
}
foreach($validAttachments as $attachment) {
$mail->AddAttachment($attachment[0], $attachment[1]);
}
}
$mail->AddAddress("example#sample.com");
if(!$mail->Send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
$counter = 1;
foreach($validAttachments as $attachment) {
move_uploaded_file( $attachment[0], "uploads/" . clean_string($name) . "_" . $counter . "_" . rand() . "_" . $attachment[1] );
$counter++;
}
}
}
You can have the paypal url as your form's action and use Ajax to save or email the form data before the form is submitted to Paypal. You can also use the Ajax response to prepare the form before submission, e.g. filling some hidden fields
Here's an example:
myform.php:
<form id="myform" method="post" action="<?php echo $paypal_url; ?>">
<input type="text" ...>
<input type="hidden" name="my-hidden-field" id="my-hidden-field" value="this is hidden">
...other form fields...
</form>
saveform.php: Processes the Ajax request and returns a response that can be used to manipulate the form before submission
<?php
if (!empty($_POST)) {
//save $_POST data to the database
//or insert your email code portion here
...
//also, fill some data as response
$response = array('my_hidden_field' => 'this is now filled in');
//next line returns the response
echo json_encode($response);
}
myform.js: Submits form data to saveform.php before submitting to paypal
$j = jQuery.noConflict();
$j(document).ready(function() {
$j('#myform').submit(submit_myform);
});
function submit_myform() {
if (!myform_is_valid()) {
window.location.href = "#myform";
return false;//prevent normal browser submission, to display validation errors
} else {
$j.ajax({
url: 'saveform.php',
type: 'POST',
data: $j(this).serialize(),
dataType:'json', //data type of Ajax response expected from server
success: myform_success //callback to handle Ajax response and submit to Paypal
});
return false;//prevent normal browser submission, since the form is submitted in the callback
}
}
function myform_is_valid() {
$valid = true;
//validate data; if there's a validation error, set $valid=false and display errors on page
...
return $valid;
}
function myform_success(response) {
//this is called whenever the ajax request returns a "200 Ok" http header
//manipulate the form as you wish
$j('#my-hidden-field').val(response.my_hidden_field);
//submit the form (to the form's action attribute, i.e $paypal_url)
document.forms['myform'].submit();
}
Instead of the jquery.ajax call you can also use the shorter:
$j.post('saveform.php',$j('#myform').serialize(),myform_success,"json")
This is to give you an idea of how you can accomplish both in one submit action.