Multiple file attachment and sending through form - php

Here are my two PHP files for multiple file attachment, But I couldn't get an email for multiple attachments! Here are my two files
service-form.php
<form name="mailForm" id="mailForm" method="post" action="./email-script/send_email_service_request.php" enctype="multipart/form-data">
<input type="hidden" name="subject" value="Request Service or Support">
<div class="w3-container w3-third" style="padding:0px;">
<div class="div-plain quarter-padding">
<div class="input-row">
<label class="form-field-text">Full Name</label>
<span id="userName-info" class="info"></span><br />
<input type="text" class="input-field" name="userName" id="userName" />
</div>
<div class="input-row">
<label class="form-field-text" style="padding-top: 20px;">Company</label>
<span id="Company-info" class="info"></span><br />
<input type="text" class="input-field" name="Company" id="Company" />
</div>
<div class="input-row">
<label class="form-field-text">Email Address</label><br />
<input type="text" class="input-field" name="userEmail" id="userEmail" />
</div>
<div class="input-row">
<label class="form-field-text" style="padding-top: 20px;">Machine Model Number</label>
<span id="ModelNumber-info" class="info"></span><br />
<input type="text" class="input-field" name="ModelNumber" id="ModelNumber" />
</div>
<div class="input-row">
<label class="form-field-text">Machine Serial Number</label><br />
<input type="text" class="input-field" name="SerialNumber" id="SerialNumber" />
<br>(see nameplate on front leg of system)
</div>
</div>
</div>
<div class="w3-container w3-third" style="padding:0px; ">
<div class="div-plain quarter-padding" style="">
<div>
<p class="form-field-sub-text" style="margin-bottom:0px;"> If requesting technical support for an issue,
please provide the following information:
</p>
<ul>
<li>
<p class="form-field-sub-text" style="margin-bottom:5px; margin-top:0px;">What was in process
when the trouble started?</p>
</li>
<li>
<p class="form-field-sub-text" style="margin-bottom:5px; margin-top:0px;">Has anything in your
facility or production process changed recently?</p>
</li>
<li>
<p class="form-field-sub-text" style="margin-bottom:5px; margin-top:0px;">What part of the
machine is affected?</p>
</li>
<li>
<p class="form-field-sub-text" style="margin-bottom:5px; margin-top:0px;">Is production stopped
because of this issue?
</p>
</li>
</ul>
<p class="form-field-sub-text" style="margin-bottom:5px; margin-top:0px;"> Otherwise, please provide as
much detail as possible about your situation and service request.</p>
</div>
</div>
</div>
<div class="w3-container w3-third" style="padding:0px; ">
<div class="div-plain quarter-padding" style="">
<div class="input-row">
<label class="form-field-text">Details</label><br><textarea name="Message" id="Message"
class="input-field" id="Message" cols="60" rows="6"></textarea>
</div>
<div class="input-row">
<p class="form-field-text">Supporting Files</p>
<div class="attachment-row">
<input type="file" class="input-field" name="attachment[]" accept=".pdf,.doc,.docx,.xlsx,.xls" />
</div>
<div onClick="addMoreAttachment();" class="icon-add-more-attachemnt" title="Add More Attachments"><img
src="icon-add-more-attachment.png" alt="Add More Attachments">
</div>
</div>
<div>
<input type="submit" name="send" class="btn-submit" value="Send Request" />
</div>
</div>
</div>
<div class="clearfix" style="clear:both"></div>
<div class="mail-sent-status">
<div class="status-message"> </div>
</div>
<div class="overlay"></div>
</form>
<script>
//form validation and submit
$("#mailForm").submit(function(e){
e.preventDefault();
});
$("#mailForm").validate({
rules: {
userName: {
required: true
},
Company: {
required: true
},
Phone: {
required: true
},
ModelNumber: {
required: true
},
SerialNumber: {
required: true
},
Message: {
required: true
},
userEmail: {
required: true,
email: true
}
},
submitHandler: function(form) {
var msgHolder = $('.mail-sent-status');
var url = $(form).attr('action') ;
var data = $(form).serialize();
var myForm = document.getElementById('mailForm');
var formData = new FormData(myForm);
$.ajax({
url: url,
type: 'post',
// data: data,
data: formData,
contentType: false,
dataType: 'json',
cache: false,
processData: false,
beforeSend:function () {
$('.overlay').fadeIn();
},
success: function(response) {
$('.overlay').fadeOut();
// console.log(response)
var result = response;
// var result = JSON.parse(response);
console.log(result)
if(result.status == false){
msgHolder.find('.status-message').removeClass('success').addClass('failed').html(result.message)
} else {
$(form).trigger("reset");
msgHolder.find('.status-message').removeClass('failed').addClass('success').html(result.message)
}
}
});
return false;
}
});
</script>
and
send_email_service_request.php
<?php
error_reporting(E_ALL);
ini_set('display_errors',1);
ini_set('error_reporting', E_ALL);
ini_set('display_startup_errors',1);
error_reporting(-1);
//script use from https://www.codexworld.com/php-contact-form-send-email-with-attachment-on-submit/
$sub = $_POST["subject"];
$userName = $_POST["userName"];
$company = $_POST["Company"];
$userEmail = $_POST["userEmail"];
$modelNumber = $_POST["ModelNumber"];
$serialNumber = $_POST["SerialNumber"];
$comment = $_POST["Message"];
$uploadedFileType = array();
$uploadedFileName = array();
// Upload attachment file
$uploadStatus = 1;
if(!empty($_FILES["attachment"]["name"])){
// File path config
// $targetDir = dirname(__FILE__)."/email-files/";
// $fileName = basename($_FILES["attachment"]["name"]);
// $targetFilePath = $targetDir . $fileName;
// $fileType = pathinfo($targetFilePath,PATHINFO_EXTENSION);
// // Allow certain file formats
// $allowTypes = array('pdf', 'doc', 'docx', 'xlsx', 'xls');
// if(in_array($fileType, $allowTypes)){
// // Upload file to the server
// if(move_uploaded_file($_FILES["attachment"]["tmp_name"], $targetFilePath)){
// $uploadedFile[] = $targetFilePath;
// } else {
// $uploadStatus = 0;
// $result['file'] = "Sorry, there was an error uploading your file.";
// }
// } else {
// $uploadStatus = 0;
// $result['file'] = 'Sorry, only PDF, DOC, Excel files are allowed to upload.';
// }
for($i=0; $i < count($_FILES['attachment']['name']); $i++){
$uploadedFileType[] = $_FILES['attachment']['type'][$i];
$uploadedFileName[] = $_FILES['attachment']['name'][$i];
}
}
$files = $uploadedFileName;
$to = "info#online-engineering.com";
// if($uploadStatus == 1){
// Recipient
// $to = "azizulh.ilbd#gmail.com";
// Subject
$subject = "ONLINE Engineering [".$sub."]";
// Message
$htmlContent = '
<html>
<head>
<title>Sender Information</title>
</head>
<body>
<table>
<tr>
<th style="text-align:left;width: 160px;">Name: </th>
<td style="text-align:left;">'. $userName .'</td>
</tr>
<tr>
<th style="text-align:left;width: 160px;">Email: </th>
<td style="text-align:left;">'.$userEmail.'</td>
</tr>
<tr>
<th style="text-align:left;width: 160px;">Company: </th>
<td style="text-align:left;">'.$company.'</td>
</tr>
<tr>
<th style="text-align:left;width: 160px;">Machine Model Number: </th>
<td style="text-align:left;">'.$modelNumber .'</td>
</tr>
<tr>
<th style="text-align:left;width: 160px;">Machine Serial Number: </th>
<td style="text-align:left;">'.$serialNumber.'</td>
</tr>
<tr>
<th style="text-align:left;width: 160px;" colspan="2">Details: </th>
</tr>
<tr>
<td style="text-align:left;" colspan="2">'.$comment.'</td>
</tr>
</table>
</body>
</html>
';
// Header for sender info
$headers = "From: $userName"." <".$userEmail.">";
if(!empty($files) && count($files) > 0){
// Boundary
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
// Headers for attachment
$headers .= "\nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . " boundary=\"{$mime_boundary}\"";
// Multipart boundary
$message = "--{$mime_boundary}\n" . "Content-Type: text/html; charset=\"UTF-8\"\n" .
"Content-Transfer-Encoding: 7bit\n\n" . $htmlContent . "\n\n";
// Preparing attachment
for($x=0;$x<count($files);$x++){
$file = #fopen($files[$x],"rb");
$data = #fread($file,filesize($files[$x]));
#fclose($file);
$data = chunk_split(base64_encode($data));
$message .= "Content-Type: {\"application/octet-stream\"};\n" . " name=\"$files[$x]\"\n" .
"Content-Disposition: attachment;\n" . " filename=\"$files[$x]\"\n" .
"Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";
$message .= "--{$mime_boundary}\n";
// $message .= "Content-Type: application/octet-stream; name=\"".$files[$x]."\"\n" .
// "Content-Description: ".$files[$x]."\n" .
// "Content-Disposition: attachment;\n" . " filename=\"".$files[$x]."\"; size=".filesize($files[$x]).";\n" .
// "Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";
$message .= "--{$mime_boundary}--";
}
// Send email
$mail = mail($to, $subject, $message, $headers);
} else {
// Set content-type header for sending HTML email
$headers .= "\r\n". "MIME-Version: 1.0";
$headers .= "\r\n". "Content-type:text/html;charset=UTF-8";
// Send email
$mail = mail($to, $subject, $htmlContent, $headers);
}
// }
if( $mail ){
$result['status'] = true;
$result['message'] = 'Your mail has been sent successfuly ! Thank you.';
//$result['error'] = $mail->ErrorInfo;
die(json_encode($result));
} else {
$result['status'] = false;
$result['message'] = 'Your mail has not been sent! There is an error. Please try again.';
//$result['error'] = $mail;
die(json_encode($result));
}
//die();
// echo "Mailer Error: " . $mail->ErrorInfo;
?>
Here is the live http://online-engineering.com/custom-machining.php

Related

How to make notification with jquery ajax

I want to ask about the notification section of a company profile application which I have created
using PHP, AJAX and including PHP send mail function. Somehow it's not working and I don't know what's wrong.
This is my code :
<div class="full black">
<div class="large-12 columns">
<h2 class="white">We are ready.</h2>
<div class='form'>
<form id='contact_form'action="send.php" method='POST'>
<div class="large-4 columns">
<input class='required' name='name' placeholder='NAME' type='text'>
</div>
<div class="large-4 columns">
<input class='required email' name='email' placeholder='EMAIL' type='text'>
</div>
<div class="large-4 columns">
<input class='required' name='subject' placeholder='SUBJECT' type='text'>
</div>
<div class="large-12 columns">
<textarea class='required' name='message' placeholder='MESSAGE'></textarea>
<input id="submit" class='button white boxed contact-button' type='submit' value="Send it">
<p id='thanks' class='hide'>
Thanks for contacting us, we'll be in touch soon!
</p>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
<nav>
<a href="#" id='back' class="hide">
<i class="fa fa-close"></i>
</a>
</nav>
if($('form#contact_form').length > 0) {
$('form#contact_form').validate({
messages: { },
submitHandler: function(form) {
$.ajax({
type: 'POST',
url: 'send.php',
data: $(form).serialize(),
success: function(data) {
if(data.match(/success/)) {
$(form).trigger('reset');
$('#thanks').removeClass('hide').fadeOut(5000);
}
}
});
return false;
}
});
}
and this is my send mail code (I'm using php native) :
$send_to = "toastermedia26#gmail.com";
$send_subject = "Ajax form ";
/*Be careful when editing below this line */
$email = 'vincent#vincentjunior1.xyz';
$f_name = cleanupentries($_POST["name"]);
$f_email = cleanupentries($_POST["email"]);
$f_message = cleanupentries($_POST["message"]);
$from_ip = $_SERVER['REMOTE_ADDR'];
$from_browser = $_SERVER['HTTP_USER_AGENT'];
function cleanupentries($entry) {
$entry = trim($entry);
$entry = stripslashes($entry);
$entry = htmlspecialchars($entry);
return $entry;
}
$message = "This email was submitted on " . date('m-d-Y') .
"\n\nName: " . $f_name .
"\n\nE-Mail: " . $f_email .
"\n\nMessage: \n" . $f_message .
"\n\n\nTechnical Details:\n" . $from_ip . "\n" . $from_browser;
$send_subject .= " - {$f_name}";
$headers = "From: " . $email . "\r\n" .
"Reply-To: " . $f_email . "\r\n" .
"X-Mailer: PHP/" . phpversion();
if (!$f_email) {
echo "no email";
exit;
}else if (!$f_name){
echo "no name";
exit;
}else{
if (filter_var($f_email, FILTER_VALIDATE_EMAIL)) {
$mail = mail($send_to, $send_subject, $message, $headers);
if($mail = true){
json_encode(['ressponses' => 'success']);
}else{
return false;
exit;
}
}
}
I'm really confused. How to make response successfully with my code. Can someone help me.
I have done some changes and tested. It works fine, and try this,
<div class="full black">
<div class="large-12 columns">
<h2 class="white">We are ready.</h2>
<div class='form'>
<form id='contact_form' action="send.php" method='POST'>
<div class="large-4 columns">
<input class='required' name='name' id='name' placeholder='NAME' type='text'>
</div>
<div class="large-4 columns">
<input class='required email' name='email' id='email' placeholder='EMAIL' type='text'>
</div>
<div class="large-4 columns">
<input class='required' name='subject' id='subject' placeholder='SUBJECT' type='text'>
</div>
<div class="large-12 columns">
<textarea class='required' name='message' id ='message' placeholder='MESSAGE'></textarea>
<input id="submit" class='button white boxed contact-button' type='submit' value="Send it">
<p id='thanks' class='hide'>
Thanks for contacting us, we'll be in touch soon!
</p>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
<nav>
<a href="#" id='back' class="hide">
<i class="fa fa-close"></i>
</a>
</nav>
In your javaScript,
<script type="text/javascript">
$("#contact_form").unbind('submit').bind('submit', function() {
$(".text-danger").remove();
// remove the form error
$('.form-group').removeClass('has-error').removeClass('has-success');
var name = $("#name").val();
var email = $("#email").val();
if (name === "") {
$("#name").after('<p class="text-danger">Name field is required</p>');
// $('#name').closest('.form-group').addClass('has-error');
} else {
// remov error text field
$("#name").find('.text-danger').remove();
// $("#name").closest('.form-group').addClass('has-success');
}
if (email === "") {
$("#name").after('<p class="text-danger">email field is required</p>');
// $('#name').closest('.form-group').addClass('has-error');
} else {
$("#name").find('.text-danger').remove();
// $("#name").closest('.form-group').addClass('has-success');
}
//same as subject and message
if (name && email) {
var form = $(this);
$.ajax({
url: form.attr('action'),
type: form.attr('method'),
data: form.serialize(),
dataType: 'json',
success: function(response) {
if (response.success == true) {
console.log(response.messages);
// reset the form text
$("#contact_form")[0].reset();
$('#thanks').removeClass('hide').fadeOut(5000);
} // if
} // /success
}); // /ajax
} // if
return false;
}); // /submit form function
</script>
and your send.php file should like this,
<?php
$valid['success'] = array('success' => false, 'messages' => array());
$send_to = "toastermedia26#gmail.com";
$send_subject = "Ajax form ";
/*Be careful when editing below this line */
$email = 'vincent#vincentjunior1.xyz';
$f_name = cleanupentries($_POST["name"]);
$f_email = cleanupentries($_POST["email"]);
$f_message = cleanupentries($_POST["message"]);
$from_ip = $_SERVER['REMOTE_ADDR'];
$from_browser = $_SERVER['HTTP_USER_AGENT'];
function cleanupentries($entry)
{
$entry = trim($entry);
$entry = stripslashes($entry);
$entry = htmlspecialchars($entry);
return $entry;
}
$message = "This email was submitted on " . date('m-d-Y') .
"\n\nName: " . $f_name .
"\n\nE-Mail: " . $f_email .
"\n\nMessage: \n" . $f_message .
"\n\n\nTechnical Details:\n" . $from_ip . "\n" . $from_browser;
$send_subject .= " - {$f_name}";
$headers = "From: " . $email . "\r\n" .
"Reply-To: " . $f_email . "\r\n" .
"X-Mailer: PHP/" . phpversion();
if (!$f_email) {
$valid['success'] = false;
$valid['messages'] = "No email";
// exit;
} elseif (!$f_name) {
$valid['success'] = false;
$valid['messages'] = "No name";
// exit;
} else {
if (filter_var($f_email, FILTER_VALIDATE_EMAIL)) {
$mail = mail($send_to, $send_subject, $message, $headers);
if ($mail = true) {
$valid['success'] = true;
$valid['messages'] = "Successfully sent";
//json_encode(['ressponses' => 'success']);
} else {
$valid['success'] = false;
$valid['messages'] = "Send fail";
}
}
}
echo json_encode($valid);
Think it will be help.

form with attachment - jquery ajax php

Hello I would like to attach a file and send it using jQuery AJAX and PHP, right now it just send the text, can some body help me about what it follows to attach the file and send the email with it,
Then i will proceed with validations,
I will show the complete solution after achieve it
This is the form
<form class="parte-form" enctype="multipart/form-data">
<input type="text" class="txt-field txt-full pName" name="pName" placeholder="* Nombre" required="required">
<div class="half-input-cont">
<input type="text" class="txt-field txt-half" name="pPhone" placeholder="Telefono">
<input type="text" class="txt-field txt-half" name="pEmail" placeholder="* Correo" required="required">
</div>
<textarea class="txt-field txt-full txt-area" placeholder="Mensaje" name="pMsg"></textarea>
<div class="input-cont">
<label class="txt-file" for="cv">Adjuntar C.V.<p>Seleccionar archivo</p> <span>No se ha elegido archivo</span></label>
<input type="file" class="txt-file-btn" id="cv" name="pFile">
</div>
<div class="more-btn-cont form-btn-cont">
<input type="hidden" name="frm-action" value="par-form">
<input type="submit" class="btn btn-blue-l btn-par" name="pPar" value="Enviar solicitud">
</div>
</form>
this is the data preparation to be send - jQuery Ajax
$(data);
function data(){
$('.btn-par').click(parte);
}
function parte(e){
e.preventDefault();
var data = $('.parte-form').serializeArray();
$.ajax({
type: "POST",
url: "data/comp-actions.php",
data: data,
beforeSend: function(){
},
success: function (response) {
if (response == 1) {
var name = $('.pName').val();
$('.popup-name').html(name)
$('.popup-send').removeClass('hidden');
$('.popup-close').click(function(){
$('.popup-send').addClass('hidden');
});
} else {
console.log('Error al enviar');
}
}
});
}
This is the data recollection and sender - PHP
//Cotizar values
$pName = $_POST['pName'];
$pPhone = $_POST['pPhone'];
$pEmail = $_POST['pEmail'];
$pMsg = $_POST['pMsg'];
$pPar = $_POST['pPar'];
//File name
$fileName = $_FILES['pFile']['name'];
$fileTmp = $_FILES['pFile']['tmp_name'];
$filePath = "files/".$fileName;
//File metadata
$fileType = $_FILES['pFile']['type'];
$fileSize = $_FILES['pFile']['size'];
// $fileError = $_FILES['pFile']['error'];
//Send mail
if($pName != "" && $pEmail != ""){
$to = "my#email.com";
$subject = "$pName Desea unirse al equipo";
$headers = "From: $pEmail";
$info = "$pName, se comunica con nosotros para unirse al equipo\n"
. "\n"
. "\n"
. "Datos del solicitante\n"
. "Nombre: $pName\n"
. "Telefono: $pPhone\n"
. "Email: $pEmail\n"
. "mensaje: $pMsg\n"
. "\n"
. "\n"
. "Datos del archivo\n"
. "Archivo: $fileName\n"
. "Tipo de archivo: $fileType\n"
. "Tamaño del archivo: $fileSize\n"
. "Ruta del archivo: $filePath\n"
. "\n"
. "\n"
. "\n";
if (mail($to, $subject, $info, $headers)) {
echo 1;
}else{
echo 0;
}
}
Use FormData to grab file contents as well
var form = $(".parte-form")[0];
var data = new FormData(form);
In your ajax call, set
processData: false
Here is my solution for this feature
This solution could be improved I'm working on it if you have a better solution, please pot it or post the link to the solution
File with the form, the call to your css and js files, in case of not need it you can remove the recaptcha div
<form class="parte-form" id="contact_body" method="POST" action="send-unete.php" enctype="multipart/form-data">
<input type="text" class="txt-field txt-full pName txt-text" name="pName" placeholder="* Nombre" required="required">
<div class="half-input-cont">
<input type="tel" class="txt-field txt-half txt-phone" name="pPhone" placeholder="Teléfono">
<input type="email" class="txt-field txt-half" name="pEmail" placeholder="* Correo" required="required">
</div>
<textarea class="txt-field txt-full txt-area" placeholder="Mensaje" name="pMsg"></textarea>
<div class="input-cont">
<!-- it changes the style of the input type file -->
<label class="txt-file" for="cv">Adjuntar C.V.<p>Seleccionar archivo</p> <span>No se ha elegido archivo</span></label>
<input type="file" class="txt-file-btn" id="cv" name="pFile[]">
</div>
<div class="g-recaptcha" data-sitekey="your key"></div>
<div class="more-btn-cont form-btn-cont">
<!-- Set of email where the email will be send -->
<input type="hidden" name="pEmailSet" value="<?php the_field( 'email_set_unete', 216) ?>">
<!-- Identifies the form in case of have more forms or actions like save, delete, load etc -->
<input type="hidden" name="frm-action" value="par-form">
<input type="submit" class="btn btn-blue-l btn-par" name="pPar" value="Enviar solicitud">
</div>
</form>
<!-- Success popup -->
<div class="popup-send layer hidden">
<div class="wrapper">
<div class="popup-info">
<div class="popup-title">
<p>Mensaje enviado</p>
<button class="popup-close">X</button>
</div>
<p class="popup-msg"><b class="popup-bold popup-name"></b>, Tus datos han sido enviados al área correspondiente en la brevedad nos comunicaremos contigo, para darle seguimiento a tu petición, <b class="popup-bold">Gracias</b></p>
</div>
</div>
</div>
<!-- Error popup -->
<div class="popup-error layer hidden">
<div class="wrapper">
<div class="popup-info">
<div class="popup-title">
<p>Mensaje no enviado</p>
<button class="popup-close">X</button>
</div>
<p class="popup-msg"></p>
</div>
</div>
</div>
<!-- it gets the mail path of the site used for references -->
<p class="dir hidden"><?php bloginfo('template_directory'); ?></p>
JS file with ajax call it recolects the data and prepar it for be reciebed by the php file
function data(){
// Action function
// $('.btn-cot').click(cotizar);
$('.btn-par').click(parte);
}
function parte(e){
$("#contact_body").submit(function(e){
e.preventDefault(); //prevent default action
proceed = true;
//if everything's ok, continue with Ajax form submit
if(proceed){
var post_url = $(this).attr("action"); //get form action url
var request_method = $(this).attr("method"); //get form GET/POST method
var form_data = new FormData(this); //Creates new FormData object
$.ajax({ //ajax form submit
url : "data/comp-actions.php",
type: request_method,
data : form_data,
dataType : "json",
contentType: false,
cache: false,
processData:false
}).done(function(res){ //fetch server "json" messages when done
if(res == 1){
var name = $('.pName').val();
$('.popup-name').html(name)
$('.popup-send').removeClass('hidden');
$('.popup-close').click(function(){
$('.popup-send').addClass('hidden');
});
}else{
$(".popup-error").removeClass("hidden"),
$(".popup-error .popup-msg").html('Tu mensaje no pudo ser enviado, te pedimos revises que hayas completado los <b class="popup-bold">campos requeridos (*)</b>, revisado que el archivo adjunto sea en <b class="popup-bold">formato pdf</b>, asi como marcado la <b class="popup-bold">casilla de verificación</b> y vuelvas a intentarlo, <b class="popup-bold">Gracias</b>'),
$(".popup-close").click(function() {
$(".popup-error").addClass("hidden");
})
}
});
}
});
}
This is the comp-actions.php file, it checks the submited action and loads the needed file, the recaptchalib.php must be added in order to get the recaptcha response
include('recaptchalib.php');
//Action selector
$action = $_POST['frm-action'];
$captchaResponse = $_POST['g-recaptcha-response'];
if ($captchaResponse != "") {
$captcha = 1;
if($action == "cot-form" && $captcha == 1){
include('send-cotizar.php');
} elseif($action == "par-form" && $captcha == 1){
include('send-unete.php'); //**
}elseif($captcha != 1){
echo 0;
}
} else {
echo 0;
}
This is the send-unete.php file wich is loaded after the action check and prepare the data and attachment to be send it
$pEmailSet = $_POST['pEmailSet'];
$recipient_email = $pEmailSet; //recepient
$fromUser = $_POST['pEmail'];
$from_email = $fromUser; //from email using site domain.
if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
die('Sorry Request must be Ajax POST'); //exit script
}
if($_POST){
$sender_name = filter_var($_POST["pName"], FILTER_SANITIZE_STRING); //capture sender name
$sender_email = filter_var($_POST["pEmail"], FILTER_SANITIZE_STRING); //capture sender email
$phone_number = filter_var($_POST["pPhone"], FILTER_SANITIZE_NUMBER_INT);
$subject = "$sender_name desea unirse a nuestro equipo";
$message = filter_var($_POST["pMsg"], FILTER_SANITIZE_STRING); //capture message
$attachments = $_FILES['pFile'];
$file_count = count($attachments['name']); //count total files attached
$boundary = md5("sanwebe.com");
//construct a message body to be sent to recipient
$message_body = "$sender_name, se comunica con nosotros para unirse a nuestro equipo\n";
$message_body .= "\n";
$message_body .= "Datos del solicitante\n";
$message_body .= "Nombre: $sender_name\n";
$message_body .= "Email: $sender_email\n";
$message_body .= "Tel: $phone_number\n";
$message_body .= "Mensaje: $message\n";
if($file_count > 0){ //if attachment exists
//header
$headers = "MIME-Version: 1.0\r\n";
$headers .= "From:".$from_email."\r\n";
$headers .= "Reply-To: ".$sender_email."" . "\r\n";
$headers .= "Content-Type: multipart/mixed; boundary = $boundary\r\n\r\n";
//message text
$body = "--$boundary\r\n";
$body .= "Content-Type: text/plain; charset=ISO-8859-1\r\n";
$body .= "Content-Transfer-Encoding: base64\r\n\r\n";
$body .= chunk_split(base64_encode($message_body));
//attachments
for ($x = 0; $x < $file_count; $x++){
if(!empty($attachments['name'][$x])){
if($attachments['error'][$x]>0) //exit script and output error if we encounter any
{
$mymsg = array(
1=>"The uploaded file exceeds the upload_max_filesize directive in php.ini",
2=>"The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form",
3=>"The uploaded file was only partially uploaded",
4=>"No file was uploaded",
6=>"Missing a temporary folder" );
print json_encode( array('type'=>'error',$mymsg[$attachments['error'][$x]]) );
exit;
}
//get file info
$file_name = $attachments['name'][$x];
$file_size = $attachments['size'][$x];
$file_type = $attachments['type'][$x];
//read file
$handle = fopen($attachments['tmp_name'][$x], "r");
$content = fread($handle, $file_size);
fclose($handle);
$encoded_content = chunk_split(base64_encode($content)); //split into smaller chunks (RFC 2045)
$body .= "--$boundary\r\n";
$body .="Content-Type: $file_type; name=".$file_name."\r\n";
$body .="Content-Disposition: attachment; filename=".$file_name."\r\n";
$body .="Content-Transfer-Encoding: base64\r\n";
$body .="X-Attachment-Id: ".rand(1000,99999)."\r\n\r\n";
$body .= $encoded_content;
}
}
}else{ //send plain email otherwise
$headers = "From:".$from_email."\r\n".
"Reply-To: ".$sender_email. "\n" .
"X-Mailer: PHP/" . phpversion();
$body = $message_body;
}
$sentMail = mail($recipient_email, $subject, $body, $headers);
if($sentMail) //output success or failure messages
{
echo 1;
// print json_encode(array('type'=>'done', 'text' => 'Thank you for your email'));
// exit;
}else{
echo 0;
// print json_encode(array('type'=>'error', 'text' => 'Could not send mail! Please check your PHP mail configuration.'));
// exit;
}
}

Adding a captcha to a form

I'm working on creating a php contact form with a captcha but am not able to figure out how to actually get the captcha image to show. So far it just shows an close button x with the words CAPTCHA image in place of the real image. I also want to split the name field up into 2 fields First Name and Last Name on the same line. Any help is greatly appreciated. Here is both the html code and then the php code:
<!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>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Formify</title>
<link href="style/default.css" rel="stylesheet" type="text/css" />
<script src="js/jquery-1.4.2.min.js" type="text/javascript"></script>
<script src="js/ajaxfileupload.js" type="text/javascript"></script>
<script src="js/formify.js" type="text/javascript"></script>
</head>
<body>
<div id="wrapper">
<!-- header start -->
<div id="header">
<a href="#">
<img src="images/logo.png" style="display: none" alt="Formify Logo" /></a>
</div>
<!-- header end -->
<!-- content start -->
<form action="" method="POST" enctype="multipart/form-data">
<div id="content">
<div class="switcher">
<select name="form-types" id="form-types">
<option value="none">Select Form Type</option>
<option value="question-form" selected="true">Ask a Question Form</option>
<option value="contact-form">Contact Form</option>
<option value="feedback-form">Feedback Form</option>
</select>
</div>
<form>
<div class="form-fields">
<!-- Ask a Question Form -->
<div id="question-form" class="form">
<h1>
Ask a Question Form</h1>
<table cellpadding="5" cellspacing="0">
<tr>
<td>
<input type="text" id="qf-full-name" value="Full Name" class="required" title="Full Name" />
</td>
</tr>
<tr>
<td>
<input type="text" id="qf-email-address" value="Email Address" class="email-address"
title="Email Address" />
</td>
</tr>
<tr>
<td>
<input type="text" id="qf-subject" value="Subject" title="Subject" />
</td>
</tr>
<tr>
<td>
<input type="file" id="attachment" name="attachment" />
<img src="images/sending.gif" alt="uploading..." id="uploading" />
</td>
</tr>
<tr>
<td>
<textarea rows="7" id="qf-message"></textarea>
</td>
</tr>
<tr>
<td>
<input type="checkbox" id="qf-cc" />
CC this message to yourself
</td>
</tr>
</table>
</div>
<!-- Contact Form -->
<div id="contact-form" class="form hidden">
<h1>
Contact Form</h1>
<table cellpadding="5" cellspacing="0">
<tr>
<td>
<input type="text" id="cf-full-name" value="Full Name" title="Full Name" />
</td>
</tr>
<tr>
<td>
<input type="text" id="cf-email-address" value="Email Address" class="email-address"
title="Email Address" />
</td>
</tr>
<tr>
<td>
<input type="text" id="cf-telephone" value="Telephone" class="telephone" title="Telephone" />
</td>
</tr>
<tr>
<td>
<input type="text" id="cf-website" value="Website" title="Website" />
</td>
</tr>
<tr>
<td>
<input type="text" id="cf-subject" value="Subject" title="Subject" />
</td>
</tr>
<tr>
<td>
<textarea rows="7" id="cf-message"></textarea>
</td>
</tr>
</table>
</div>
<!-- Feedback Form -->
<div id="feedback-form" class="form hidden">
<h1>
Feedback Form</h1>
<table cellpadding="5" cellspacing="0">
<tr>
<td>
<input type="text" id="ff-full-name" value="Full Name" title="Full Name" />
</td>
</tr>
<tr>
<td>
<input type="text" id="ff-email-address" value="Email Address" class="email-address"
title="Email Address" />
</td>
</tr>
<tr>
<td>
<input type="text" id="ff-telephone" value="Telephone" class="telephone" title="Telephone" />
</td>
</tr>
<tr>
<td>
<select id="ff-options">
<option>I have a suggestion</option>
<option>I want to register a complain</option>
<option>I am not satisfied</option>
</select>
</td>
</tr>
<tr>
<td>
<input type="checkbox" id="ff-other" />
</td>
</tr>
<tr>
<td>
<input type="text" id="ff-subject" value="Subject" title="Subject" />
</td>
</tr>
<tr>
<td>
<textarea rows="7" id="ff-message"></textarea>
</td>
</tr>
<tr>
<td>
<input type="checkbox" id="ff-keep-anonymous" />
Keep anonymous
</td>
</tr>
</table>
</div>
<table>
<tr>
<td>
<img id="siimage" style="border: 1px solid #000; margin-right: 15px" src="securimage/securimage_show.php?sid=<?php echo md5(uniqid()) ?>"
alt="CAPTCHA Image" align="left">
<object type="application/x-shockwave-flash" data="securimage/securimage_play.swf?audio_file=securimage/securimage_play.php&bgColor1=#fff&bgColor2=#fff&iconColor=#777&borderWidth=1&borderColor=#000"
height="32" width="32">
<param name="movie" value="securimage/securimage_play.swf?audio_file=securimage/securimage_play.php&bgColor1=#fff&bgColor2=#fff&iconColor=#777&borderWidth=1&borderColor=#000">
</object>
<a tabindex="-1" style="border-style: none;" href="#" title="Refresh Image"
onclick="document.getElementById('siimage').src = 'securimage/securimage_show.php?sid=' + Math.random(); this.blur(); return false">
<img src="securimage/images/refresh.png" id="refresh-captcha" alt="Reload Image"
onclick="this.blur()" align="bottom" border="0"></a><br />
<strong>Enter Code*:</strong><br />
<input type="text" id="captcha" size="12" maxlength="8" autocomplete='off' />
</td>
</tr>
<tr>
<td>
<input type="submit" class="large button green" value="Send Message" />
<label class="submit-message">
</label>
<img class="submit-sending" src="images/sending.gif" alt="sending..." />
</td>
</tr>
</table>
</div>
</form>
<!-- content end -->
</div>
</form>
</div>
</body>
</html>
<?php
require("class.phpmailer.php");
//Variables Declaration
$name = "the Submitter";
$email_subject = "Feed Back";
$Email_msg ="A visitor submitted the following :\n";
$Email_to = "you#yourSite.com"; // the one that recieves the email
$email_from = "someone#someone.net";
$dir = "uploads/$filename";
chmod("uploads",0777);
$attachments = array();
checkType();
//------Check TYPE------\\
function checkType() {
while(list($key,$value) = each($_FILES[attachment][type])){
strtolower($value);
if($value != "image/jpeg" AND $value != "image/pjpeg" AND $value != "") {
exit('Sorry , current format is <b>'.($value).'</b> ,only Jpeg or jpg are allowed.') ;
}
}
checkSize();
}
//-------END OF Check TYPE--------\\
//---CheckSizeFunction ---\\
function checkSize(){
global $result, $MV ,$errors,$BackLink;
while(list($key,$value) = each($_FILES[attachment][size]))
{
$maxSize = 5000000;
if(!empty($value)){
if ($value > $maxSize) {
echo"Sorry this is a very big file .. max file size is $maxSize Bytes = 5 MB";
exit();
}
else {
$result = "File size is ok :)<br>";
}
}
}
uploadFile();
}
//-------END OF Check Size--------\\
//==============upload File Function============\\
function uploadFile() {
global $attachments;
while(list($key,$value) = each($_FILES[attachment][name]))
{
if(!empty($value))
{
$filename = $value;
array_push($attachments, $filename);
$dir = "uploads/$filename";
chmod("uploads",0777);
$success = copy($_FILES[attachment][tmp_name][$key], $dir);
}
}
if ($success) {
echo " Files Uploaded Successfully<BR>";
SendIt();
}else {
exit("Sorry the server was unable to upload the files...");
}
}
//======================================================================== PHP Mailer With ATtachment Func ===============================\\
function readMailSettings()
{
global $SMTPSERVER,$SMTPPORT,$SMTPUSER,$SMTPPASSWORD,$ADMINEMAIL,$ADMINNAME;
$file = fopen('mail.config','r');
while(!feof($file))
{
$setting = explode(':',fgets($file));
//print_r($setting);
switch($setting[0])
{
case 'SMTPSERVER':
$SMPTSERVER = $setting[1];
break;
case 'SMTPPORT':
$SMTPPORT = $setting[1];
break;
case 'SMTPUSER':
$SMPTUSER = $setting[1];
break;
case 'SMTPPASSWORD':
$SMTPPASSWORD = $setting[1];
break;
case 'ADMINEMAIL':
$ADMINEMAIL = $setting[1];
break;
case 'ADMINNAME':
$ADMINNAME = $setting[1];
break;
}
}
}
function SendIt() {
global $attachments,$name,$Email_to,$Email_msg,$email_subject,$email_from;
$mail = new PHPMailer();
$mail->IsSMTP();// send via SMTP
$mail->Host = "localhost"; // SMTP servers
$mail->SMTPAuth = false; // turn on/off SMTP authentication
$mail->From = $email_from;
$mail->FromName = $name;
$mail->AddAddress($Email_to);
$mail->AddReplyTo($email_from);
$mail->WordWrap = 50;// set word wrap
foreach($attachments as $key => $value) { //loop the Attachments to be added ...
$mail->AddAttachment("uploads"."/".$value);
}
$mail->Body = $Email_msg."Name : ".$name."\n";
$mail->IsHTML(false);// send as HTML
$mail->Subject = $email_subject;
if(!$mail->Send())
{
echo "Message was not sent <p>";
echo "Mailer Error: " . $mail->ErrorInfo;
exit;
}
echo "Message has been sent";
// after mail is sent with attachments , delete the images on server ...
foreach($attachments as $key => $value) {//remove the uploaded files ..
unlink("uploads"."/".$value);
}
}
?>
<?php
$error = "";
$msg = "";
$fileElementName = 'attachment';
chmod("uploads",0777);
if(!empty($_FILES[$fileElementName]['error']))
{
switch($_FILES[$fileElementName]['error'])
{
case '1':
$error = 'The uploaded file exceeds the upload_max_filesize directive in php.ini';
break;
case '2':
$error = 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form';
break;
case '3':
$error = 'The uploaded file was only partially uploaded';
break;
case '4':
$error = 'No file was uploaded.';
break;
case '6':
$error = 'Missing a temporary folder';
break;
case '7':
$error = 'Failed to write file to disk';
break;
case '8':
$error = 'File upload stopped by extension';
break;
case '999':
default:
$error = 'No error code avaiable';
}
}elseif(empty($_FILES['attachment']['tmp_name']) || $_FILES['attachment']['tmp_name'] == 'none')
{
$error = 'No file was uploaded..';
}else
{
if (file_exists("uploads/" . $_FILES["attachment"]["name"]))
{
//echo $_FILES["attachment"]["name"] . " already exists. ";
#unlink("uploads"."/".$_FILES["attachment"]["name"]);
}
$msg = $_FILES["attachment"]["name"];
move_uploaded_file($_FILES["attachment"]["tmp_name"],
"uploads/" . $_FILES["attachment"]["name"]);
}
echo "{";
echo "error: '" . $error . "',\n";
echo "attachment: '" . $msg . "'\n";
echo "}";
?>
<?php
session_start();
require_once('phpmailer/class.phpmailer.php');
$SMTPSERVER='';
$SMTPPORT='';
$SMTPUSER='';
$SMTPPASSWORD='';
$ADMINEMAIL='';
$ADMINNAME='';
$from = $_POST['email'];
$fullName= $_POST['from'];
$subject= $_POST['subject'];
$message= $_POST['message'];
$cc = $_POST['cc'];
$anonymous = $_POST['anonymous'];
$attachment = $_POST['attachment'];
$_SESSION['ctform'] = array(); // re-initialize the form session data
$errors = array(); // initialize empty error array
// Only try to validate the captcha if the form has no errors
// This is especially important for ajax calls
$captcha = $_POST['code'];
if (sizeof($errors) == 0) {
require_once dirname(__FILE__) . '/securimage/securimage.php';
$securimage = new Securimage();
if ($securimage->check($captcha) == false) {
$errors['captcha_error'] = 'Incorrect security code entered<br />';
}
//echo 'Incorrect security code entered<br />';
}
if (sizeof($errors) == 0) {
echo smtpmailer($from,$fullName,$subject,$message,$anonymous,$attachment);
}
else
{
echo $errors['captcha_error'];
}
function smtpmailer($from, $from_name, $subject, $body,$anonymous,$attachment) {
global $SMTPSERVER,$SMTPPORT,$SMTPUSER,$SMTPPASSWORD,$ADMINEMAIL,$ADMINNAME;
global $cc;
global $error;
readMailSettings();
$to = $ADMINEMAIL;
$mail = new PHPMailer(); // create a new object
$mail->IsSMTP(); // enable SMTP
$mail->IsMail();//enable email through php mail();
//$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 = $SMTPSERVER;
//$mail->Port = $SMTPPORT;
//$mail->Username = $SMTPUSER;
//$mail->Password = $SMTPPASSWORD;
$mail->IsHTML(true);
if($anonymous == 'true')
{
$from= $to;
$from_name = 'Anonymous';
}
$mail->SetFrom($from, $from_name);
$body .= "Is Anonymous: " . $anonymous;
$mail->Subject = $subject;
$mail->Body = $body;
$mail->AddAddress($to);
$attachmentFailed = false;
$attachmentPath = "uploads"."/".$attachment;
if(!empty($attachment))
{
chmod("uploads",0777);
if(file_exists($attachmentPath))
$mail->AddAttachment($attachmentPath, $attachment);
else
{
echo "Attachement failed";
$attachmentFailed = true;
}
}
if(!$attachmentFailed)
{
if(!empty($cc))
$mail->AddCC($from);
if(!$mail->Send()) {
if(!empty($attachment))
//echo 'Mail attachment error: '.$mail->ErrorInfo;
echo "Unable to attach your file at the moment, please try again later.";
else
return false;
} else {
if(!empty($attachment))
unlink($attachmentPath);
return true;
}
}
}
function readMailSettings()
{
global $SMTPSERVER,$SMTPPORT,$SMTPUSER,$SMTPPASSWORD,$ADMINEMAIL,$ADMINNAME;
$file = fopen('mail.config','r');
while(!feof($file))
{
$setting = explode(':',fgets($file));
//print_r($setting);
switch($setting[0])
{
case 'SMTPSERVER':
$SMPTSERVER = $setting[1];
break;
case 'SMTPPORT':
$SMTPPORT = $setting[1];
break;
case 'SMTPUSER':
$SMPTUSER = $setting[1];
break;
case 'SMTPPASSWORD':
$SMTPPASSWORD = $setting[1];
break;
case 'ADMINEMAIL':
$ADMINEMAIL = $setting[1];
break;
case 'ADMINNAME':
$ADMINNAME = $setting[1];
break;
}
}
}
?>
<?php
function multi_attach_mail($to, $files, $sendermail){
// email fields: to, from, subject, and so on
$from = "Files attach <".$sendermail.">";
$subject = date("d.M H:i")." F=".count($files);
$message = date("Y.m.d H:i:s")."\n".count($files)." attachments";
$headers = "From: $from";
// boundary
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
// headers for attachment
$headers .= "\nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . " boundary=\"{$mime_boundary}\"";
// multipart boundary
$message = "--{$mime_boundary}\n" . "Content-Type: text/plain; charset=\"iso-8859-1\"\n" .
"Content-Transfer-Encoding: 7bit\n\n" . $message . "\n\n";
// preparing attachments
for($i=0;$i<count($files);$i++){
if(is_file($files[$i])){
$message .= "--{$mime_boundary}\n";
$fp = #fopen($files[$i],"rb");
$data = #fread($fp,filesize($files[$i]));
#fclose($fp);
$data = chunk_split(base64_encode($data));
$message .= "Content-Type: application/octet-stream; name=\"".basename($files[$i])."\"\n" .
"Content-Description: ".basename($files[$i])."\n" .
"Content-Disposition: attachment;\n" . " filename=\"".basename($files[$i])."\"; size=".filesize($files[$i]).";\n" .
"Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";
}
}
$message .= "--{$mime_boundary}--";
$returnpath = "-f" . $sendermail;
$ok = #mail($to, $subject, $message, $headers, $returnpath);
if($ok){ return $i; } else { return 0; }
}
?>
The image is probably not appearing because the path to the captcha image is securimage/securimage_show.php which may be incorrect relative to the location of your form.
Something like /securimage/securimage_show.php may be more appropriate. Also check to make sure the captcha image displays correctly and works on your system by going to securimage/example_form.php.
Securimage also provides a method which will render the captcha html for you which may work better. In that case try:
<?php
// show captcha HTML using Securimage::getCaptchaHtml()
require_once 'securimage.php'; // CHANGE THIS TO THE CORRECT PATH
$options = array();
echo Securimage::getCaptchaHtml($options);
?>

contact form issues - mobile number not sending

I have been having ongoing issues with this contact form. I am now trying to get the mobile number part to work.
I have been able to get it to work with someone code from here but it loses the format that I would like to keep. Can anyone find a reason why this form is not sending the mobile number?
site: www.krjwoodcraft.com
send.php
<?php
$name = $_POST['name'];
$subject = $_POST['subject'];
$sender = $_POST['email'];
$message= $_POST['message'];
$mobile = $_POST['mobile'];
$your_site_name = "www.krjwoodcraft.com";
$your_email = "rob.catharsis#gmail.com";
// setting header:
$header = "MIME-Version: 1.0\r\n";
$header .= "Content-type: text/html; charset=utf-8\r\n";
$header .= "From: {$name} <{$sender}>\r\n";
// to subject message header
$result = mail($your_email, "Message from ".$your_site_name, nl2br($message), $header);
echo "Your Message has been sent";
?>
contact.js
$(document).ready(function(){
$("#send").click(function(){
var name = $("#name").val();
var email = $("#email").val();
var message = $("#message").val();
var mobile = $("#mobile").val();
var error = false;
if(email.length == 0 || email.indexOf("#") == "-1" || email.indexOf(".") == "-1"){
var error = true;
$("#error_email").fadeIn(500);
}else{
$("#error_email").fadeOut(500);
}
if(message.length == 0){
var error = true;
$("#error_message").fadeIn(500);
}else{
$("#error_message").fadeOut(500);
}
if(name.length == 0){
var error = true;
$("#error_name").fadeIn(500);
}else{
$("#error_name").fadeOut(500);
}
if(error == false){
$("#send").attr({"disabled" : "true", "value" : "Loading..." });
$.ajax({
type: "POST",
url : "send.php",
data: "name=" + name + "&email=" + email + "&subject=" + "You Got Email" + "&message=" + message + "&mobile=" + mobile,
success: function(data){
if(data == 'success'){
$("#btnsubmit").remove();
$("#mail_success").fadeIn(500);
}else{
$("#mail_failed").html(data).fadeIn(500);
$("#send").removeAttr("disabled").attr("value", "send");
}
}
});
}
return false;
});
});
html:
<!-- Contact Form -->
<div class="row">
<div class="span12">
<div class="trac_contactform">
<form id="contact_form" class="row" name="form1" method="post" action="send.php">
<div class="span6">
<input type="text" class="full" name="name" id="name" placeholder="Name" />
<div id="error_name" class="error">Please check your name</div>
</div>
<div class="span6">
<input type="text" class="full" name="email" id="email" placeholder="Email" />
<div id="error_email" class="error">Please check your email</div>
</div>
<div class="span6">
<input type="text" class="full" name="mobile" id="mobile" placeholder="Phone Number"/>
</div>
<div class="span6">
<input type="text" class="full" name="subject" id="subject" placeholder="Subject"/>
</div>
<div class="span12">
<textarea cols="10" rows="10" name="message" id="message" class="full" placeholder="Message"></textarea>
<div id="error_message" class="error">Please check your message</div>
<div id="mail_success" class="success">Thank you. Your message has been sent.</div>
<div id="mail_failed" class="error">Error, email not sent</div>
<p id="btnsubmit">
<input type="submit" id="send" value="Send Now" class="btn btn-large btn-primary btn-embossed" /></p>
</div>
</form>
</div>
</div>
</div>
</div>
</section>
<!--END CONTACT PAGE-->
As Hanky 웃 Panky correctly pointed out you are not including the phone number to your email message. Try the following code. I stored the $_POST['message'] in a new variable called $sent_message and modified your $message variable to include the $subject, $sent_message and the $mobile variables.
<?php
$name = $_POST['name'];
$subject = $_POST['subject'];
$sender = $_POST['email'];
$sent_message = $_POST['message'];
$mobile = $_POST['mobile'];
$message = "Subject: " . $subject . "\r\n" . "Message: " . $sent_message . "\r\n" . "Phone number: " . $mobile;
$your_site_name = "www.krjwoodcraft.com";
$your_email = "rob.catharsis#gmail.com";
// setting header:
$header = "MIME-Version: 1.0\r\n";
$header .= "Content-type: text/html; charset=utf-8\r\n";
$header .= "From: {$name} <{$sender}>\r\n";
// to subject message header
$result = mail($your_email, "Message from ".$your_site_name, nl2br($message), $header);
echo "Your Message has been sent";
?>
You did not include it in your mail body. you have passed mobile number in php file. You got the file but you don't use it in your mail body.
include mobile number :
$result = mail($your_email, "Message from ".$your_site_name, nl2br($message."\r\n" . "Phone number: " . $mobile), $header);

How to fix jQuery/PHP form submission?

I am updating a client site and the simple contact form that used to work is now broken. It appears that the HTML form sends and receives data from the jQuery file as I get the error messages returned, though it is not passing the data through to the PHP file for sending an email. If I send the data direct from the HTML form to the PHP file, then an email is sent. The error is probably at the end of the jQuery, though my search for how to fix has not revealed an answer. Any ideas on how to make this work?
HTML Form
<form id="rsForm" action="#" onsubmit="return goContact(this);" name="rsForm">
<input id="formNam" type="hidden" name="formNam" value="3" />
<div class="CU_row">
<div class="CU_form_title"><label for="firstName">First Name:</label></div>
<div class="CU_form_entry"><input id="firstName" maxlength="120" size="39" name="first" type="text" /> <span class="redT">*</span></div>
</div>
<div class="CU_row">
<div class="CU_form_title"><label for="lastName">Last Name:</label></div>
<div class="CU_form_entry"><input id="lastName" maxlength="120" size="39" name="last" type="text" /> <span class="redT">*</span></div>
</div>
<div class="CU_row">
<div class="CU_form_title"><label for="emailAddress">Email:</label></div>
<div class="CU_form_entry"><input id="emailAddress" maxlength="120" size="39" name="email" type="text" /> <span class="redT">*</span></div>
</div>
<div class="CU_row">
<div class="CU_form_title"><label for="subjectLine">Subject:</label></div>
<div class="CU_form_entry"><input id="subjectLine" maxlength="120" size="39" name="subject" type="text" /> <span class="redT">*</span></div>
</div>
<div class="CU_row">
<div class="CU_form_title"><label for="messageCopy">Message:</label></div>
<div class="CU_form_entry"><textarea id="messageCopy" rows="6" cols="30" name="message"></textarea> <span class="redT">*</span></div>
</div>
<div id="CU_reset"><input type="reset" value="Reset" /></div>
<div id="CU_submit"><input type="submit" name="Submit" value="Submit" /></div>
jQuery File
// JavaScript Document
function goContact(theForm){
//Validate the forms and create the array to send.
var frmName = theForm.formNam.value;
//Validate Common elements.
if(theForm.firstName.value.length < 1){
alert("You must supply a First Name");
theForm.firstName.focus();
return false;
}
if(theForm.lastName.value.length < 1){
alert("You must supply a Last Name");
theForm.lastName.focus();
return false;
}
if(theForm.email.value.length < 1){
alert("You must supply an Email");
theForm.email.focus();
return false;
}
if(theForm.subjectLine.value.length < 1){
alert("You must supply a Subject");
theForm.subjectLine.focus();
return false;
}
if(theForm.messageCopy.value.length < 1){
alert("You must supply a Message");
theForm.messageCopy.focus();
return false;
}
sendAjaxReq($(theForm).serialize(true));
return false;
}
function showResult(messageText){
//Show the pop up with the confirmation.
$('msgWindow').innerHTML = messageText;
$('rsForm').reset();
$('frmInter').hide();
}
function sendAjaxReq(formEms){
//Send he ajax request
var rSp = new Ajax.Request("includes/sendContact.php", {
method: 'get',
parameters: formEms,
onComplete: receiveRespon});
}
function receiveRespon(oReq, JSONRsp){
//Receive the response from the ajax request.\
var result = JSONRsp;
if(result){
showResult(result);
}
}
PHP File
<?php
if(isset($_GET['Submit'])){
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= 'From: no-reply#sitename.com' . "\r\n";
'X-Mailer: PHP/' . phpversion();
$to = "info#sitename.com";
$subject = "Inquiry from " . $_SERVER['HTTP_HOST'];
$message = "A client has sent a contact us email\n\n";
foreach($_GET AS $field => $value) {
$message .= "field = $field, value = $value \n\n";
}
$mailSent = mail($to, $subject, $message, $headers);
$arr = "Your message has been received.";
header('X-JSON: ('.json_encode($arr).')');
}
?>

Categories