This question already has answers here:
"Notice: Undefined variable", "Notice: Undefined index", "Warning: Undefined array key", and "Notice: Undefined offset" using PHP
(29 answers)
Send attachments with PHP Mail()?
(16 answers)
Closed 3 years ago.
I have a html bootstrap form and have a php code that sends a email of form information. This has a google reCaptcha check before the email is sent.
I copied the code that does the validation of the text, the email sending and the recaptcha from another php form that works.
How can I make the php code send the 2 images it receives from the form bootstrap form as attachments in the email.
These are my file upload form elements
<form role="form" class="form" action='https://opeturmo.com/parapente_ecuador/competencia_form.php' method='post'>
<div class="form-group row">
<div class="col-12"><label for="photo">Adjunte su foto - Add a photo of you</label></div>
<div class="col-12"><p>IMPORTANTE: Adjunta una foto de tu cara. No de tu parapente o alguna otra cosa. Máx 10MB Tamaño: mayor de 400*400 px –IMPORTANT: A photo of your face. Not your glider or anything else. Max 10MB Size: not less than 400*400 px</p></div>
<div class="col-12"><input type="file" class="form-control-file" id="photo" accept="image/*" name="my_file"></div>
</div>
<div class="form-group">
<label for="pago">Adjunte su foto de pago - Add your payment photo</label>
<p>IMPORTANTE: Adjunta una foto de tu cara. No de tu parapente o alguna otra cosa. Máx 10MB Tamaño: mayor de 400*400 px –IMPORTANT: A photo of your face. Not your glider or anything else. Max 10MB Size: not less than 400*400 px</p>
<input type="file" class="form-control-file" id="pago" >
</div>
and this is my php
<?php
//Checking For reCAPTCHA
$captcha;
if (isset($_POST['g-recaptcha-response'])) {
$captcha = $_POST['g-recaptcha-response'];
}
// Checking For correct reCAPTCHA
$response = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=6LcPkZEUAAAAAL4DJYl-y3iOl1TdavmqhsghRXeU&response=" . $captcha . "&remoteip=" . $_SERVER['REMOTE_ADDR']);
if (!$captcha || $response.success == false) {
header('location: ' . $_SERVER['HTTP_REFERER']);
} else {
/* Check all form inputs using check_input function */
function check_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if( isset($_POST) ){
//user sumbission data
$ipaddress = $_SERVER['REMOTE_ADDR'];
$date_sent = date('d/m/Y');
$time = date('H:i:s');
//form data
$email = check_input($_POST['email']);
//photo
$file_name = $_FILES['my_file']['photo'];
$participant_number = check_input($_POST['participant_number']);
$firstName = check_input($_POST['firstName']);
$lastName = check_input($_POST['lastName']);
$country = check_input($_POST['country']);
$sexo = check_input($_POST['sexo']);
$date = check_input($_POST['date']);
$direccion = check_input($_POST['direccion']);
$tel = check_input($_POST['tel']);
$equipo = check_input($_POST['equipo']);
$homologacion = check_input($_POST['homologacion']);
$sponsor = check_input($_POST['sponsor']);
$licenciaFAI = check_input($_POST['licenciaFAI']);
$civilId = check_input($_POST['civilId']);
$team = check_input($_POST['team']);
$camisa = check_input($_POST['camisa']);
$seguro = check_input($_POST['seguro']);
$seguronumber = check_input($_POST['seguronumber']);
$emergencyContact = check_input($_POST['emergencyContact']);
$emergencyNumber = check_input($_POST['emergencyNumber']);
$sangre = check_input($_POST['sangre']);
//pago foto
$file_pago = $_FILES['file_pago']['pago'];
//send email if all is ok
$headers = "From: opeturmo#opeturmo.com" . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$emailbody = "<h2>Booking - Reservas</h2>
<p><strong>Email: </strong> {$email} </p>
<p><strong>Nuero participante: </strong> {$participant_number} </p>
<p><strong>Nombre: </strong> {$firstName} </p>
<p><strong>Apellido: </strong> {$lastName} </p>
<p><strong>Pais: </strong> {$country} </p>
<p><strong>Sexo: </strong> {$sexo} </p>
<p><strong>Fecha: </strong> {$date} </p>
<p><strong>Direccion: </strong> {$direccion} </p>
<p><strong>Telefono: </strong> {$tel} </p>
<p><strong>Marca equipo parapente: </strong> {$equipo} </p>
<p><strong>Sponsor: </strong> {$sponsor} </p>
<p><strong>Licencia Fai: </strong> {$licenciaFAI} </p>
<p><strong>Civil Id: </strong> {$civilId} </p>
<p><strong>Equipo con quien compute: </strong> {$team} </p>
<p><strong>Talla camisa: </strong> {$camisa} </p>
<p><strong>Compania Seguros: </strong> {$seguro} </p>
<p><strong>Poliza numero : </strong> {$seguronumber} </p>
<p><strong>Contacto de Emergencia : </strong> {$emergencyContact} </p>
<p><strong>Numero de Contacto de Emergencia : </strong> {$emergencyNumber} </p>
<p><strong>Tipo de Sangre : </strong> {$sangre} </p>
<p>This message was sent from the IP Address: {$ipaddress} on {$date_sent} at {$time}</p>";
$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;
mail ("opeturmo#gmail.com","Formulario Competencia",$emailbody,$body, $headers);
//redirect back to form
header('location: ' . $_SERVER['HTTP_REFERER']);
}
}
?>
I haven't done much with php so I am lost with this.
Related
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;
}
}
This question already has answers here:
PHP mail function doesn't complete sending of e-mail
(31 answers)
Closed 5 years ago.
HTML Code:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>BuddyTeam | Website</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
<div id="page-wrap">
<img src="images/title.png" alt="BuddyTeam | Website" /><br /><br />
<div id="contact-area">
<form method="post" action="contactengine.php">
<p style="text-align:right" onclick="alert('Só podes registar uma conta secundária se tiveres uma principal! Neste espaço escreve o Nickname da tua conta registada no Servidor.')"><font color="blue">Precisas de ajuda? Clica Aqui!</font></p>
<label for="Nickname"></label>
<p><font face="serif"></font></p><input type="text" name="Nickname" id="Nickname" placeholder="Informa o Nickname da conta principal registada no Servidor." required />
<p style="text-align:right" onclick="alert('Para não haver fraudes precisamos de saber que és mesmo tu! Vai ao Servidor com a tua conta registada, usa o comando ( /meuid ) e escreve os números neste espaço.')"><font color="blue">Precisas de ajuda? Clica Aqui!</font></p>
<label for="ID"></label>
<p><font face="serif"></font></p><input type="text" name="ID" id="ID" placeholder="Informa o ID da conta principal registada no Servidor." required />
<p style="text-align:right" onclick="alert('Contas nunca são demais! Neste espaço escreve o Nickname da nova conta que queres registar.')"><font color="blue">Precisas de ajuda? Clica Aqui!</font></p>
<label for="Novo"></label>
<input type="text" name="Novo" id="Novo" placeholder="Informa o Nickname da conta que pretendes registar." required />
<p style="text-align:right" onclick="alert('Segurança em primeiro lugar! Neste espaço escreve uma senha para a nova conta que queres registar.')"><font color="blue">Precisas de ajuda? Clica Aqui!</font></p>
<label for="Senha"></label>
<input type="text" name="Senha" id="Senha" placeholder="Informa uma senha para a tua nova conta." required />
<p style="text-align:right" onclick="alert('Depois entra em contacto! Coloca aqui o teu Email para seres contacto quando a conta for registada.')"><font color="blue">Precisas de ajuda? Clica Aqui!</font></p>
<label for="Email"></label>
<input type="text" name="Email" id="Email" placeholder="Informa um Email para contacto.">
<input type="submit" name="submit" value="Enviar" class="submit-button" />
</form>
<div style="clear: both;"></div>
</div>
</div>
</body>
</html>
PHP Code:
<?php
$EmailFrom = "geral#buddyplays.net";
$EmailTo = "geral#buddyplays.net";
$Subject = "Novo Pedido de Registo de Conta";
$Nickname = Trim(stripslashes($_POST['Nickname']));
$ID = Trim(stripslashes($_POST['ID']));
$Novo = Trim(stripslashes($_POST['Novo']));
$Senha = Trim(stripslashes($_POST['Senha']));
$Email = Trim(stripslashes($_POST['Email']));
// validation
$validationOK=true;
if (!$validationOK) {
print "<meta http-equiv=\"refresh\" content=\"0;URL=erro.html\">";
exit;
}
// prepare email body text
$Body = "";
$Body .= "Conta Registada: ";
$Body .= $Nickname;
$Body .= "\n";
$Body .= "ID da Conta Registada: ";
$Body .= $ID;
$Body .= "\n";
$Body .= "Nova Conta: ";
$Body .= $Novo;
$Body .= "\n";
$Body .= "Senha: ";
$Body .= $Senha;
$Body .= "\n";
$Body .= "Email: ";
$Body .= $Email;
$Body .= "\n";
// send email
$success = mail($EmailTo, $Subject, $Body, "From: <$EmailFrom>");
// redirect to success page
if ($success){
print "<meta http-equiv=\"refresh\" content=\"0;URL=concluido.php\">";
}
else{
print "<meta http-equiv=\"refresh\" content=\"0;URL=erro.html\">";
}
?>
When I fill out the form and submit, I'm redirected to "erro.html" and the email is not sent. What is wrong?
The system stops working from one moment to another without me doing any kind of editing.
What do I need to change for the system to work again?
The problem is that your mail() function isn't working because you have supplied an invalid fourth parameter (as your From address). "From: <$EmailFrom>" shouldn't have the brackets around the email address. If you do make use of the brackets, you need to supply a name in front of them.
Instead of $success = mail($EmailTo, $Subject, $Body, "From: <$EmailFrom>");
What you're looking to do is add it as a header:
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'From: ' . $Nickname. ' <' . $EmailFrom . '>';
$success = mail($EmailTo, $Subject, $Body, $headers);`
This will evaluate to: From: $Nickname <$EmailFrom>.
Also note that some mail servers prevent the From address from being manipulated in order to prevent phishing.
You're getting a 404 simply because erro.html doesn't exist on your server. Creating the relevant file will resolve the error and redirect you there automatically when there's an error sending of the email.
Hope this helps! :)
This question already has answers here:
"Notice: Undefined variable", "Notice: Undefined index", "Warning: Undefined array key", and "Notice: Undefined offset" using PHP
(29 answers)
Closed 6 years ago.
I am trying to add a telephone field into a contact form but when I do, the script stops working and I don´t receive an email.
<?php
// check if fields passed are empty
if(empty($_POST['name']) ||
empty($_POST['email']) ||
empty($_POST['telephone']) ||
empty($_POST['message']) ||
!filter_var($_POST['email'],FILTER_VALIDATE_EMAIL))
{
echo "No se ha introducido toda la información.";
return false;
}
$name = $_POST['name'];
$email_from = $_POST['email'];
$telephone = $_POST['telephone'];
$message = $_POST['message'];
// create email body and send it
$to = 'h.........#gmail.com'; // put your email
$email_subject = "Formulario de Contacto Con la Mochila al Hombro";
$email_body = "Has recibido un mensaje desde el formulario de contacto de la Web. \n\n".
"Aquí están los detalles:\n\n".
"Nombre: $name \n\n".
"Email: $email_from\n\n".
"Teléfono: $telephone\n\n".
"Mensaje: $message";
$headers = 'From: '.$email_from."\r\n".
'X-Mailer: PHP/' . phpversion();
mail($to,$email_subject,$email_body,$headers);
return true;
?>
And this is the html I am using:
<div class="control-group">
<div class="controls">
<input type="phone" class="form-control" placeholder="Teléfono" id="telephone" required data-validation-required-message="Por favor, dinos tu teléfono para que podamos contactar contigo." />
</div>
</div>
The form works perfectly fine if I don´t put the telephone in the php script, but as soon as I add it, it stops working. I am assuming I am setting some values wrong but I really don´t know much abut PHP.
I believe now that it is a problem with the AJAX validation script.You can see the script live in here http://talleresnaj2.com/js/contacto.min.js
Your <input /> doesn't have a name attribute, hence its value is never sent to the PHP script, making empty($_POST['telephone']) return true.
You just need to add name="telephone" in your input.
You forgot to add the input name.
Try
<input name="telephone" type="phone" class="form-control" placeholder="Teléfono" id="telephone" required data-validation-required-message="Por favor, dinos tu teléfono para que podamos contactar contigo." />
Hi I'm new at PHP and I need some help with my code.
The problem : I want to send a mail with checkbox values if they are checked, but I can't, and I don't know how to solve this issue.
Here's my code.
HTML
<div class="form-group">
<label for="jours">Choix des jours de travail</label>
<label class="checkbox">
<input type="checkbox" name="time[]"value="Lundi"> Lundi
</label>
<label class="checkbox">
<input type="checkbox" name="time[]"value="Mardi"> Mardi
</label>
<label class="checkbox">
<input type="checkbox" name="time[]"value="Mercredi"> Mercredi
</label>
<label class="checkbox">
<input type="checkbox" name="time[]"value="Jeudi"> Jeudi
</label>
<label class="checkbox">
<input type="checkbox" name="time[]"value="Vendredi"> Vendredi
</label>
<label class="checkbox">
<input type="checkbox" name="time[]"value="Samedi"> Samedi
</label>
</div>
PHP
<?php
if(empty($_POST['name']) ||
empty($_POST['email']) ||
empty($_POST['phone']) ||
!filter_var($_POST['email'],FILTER_VALIDATE_EMAIL))
{
echo "No arguments Provided!";
return false;
}
$name = strip_tags(htmlspecialchars($_POST['name']));
$email_address = strip_tags(htmlspecialchars($_POST['email']));
$phone = strip_tags(htmlspecialchars($_POST['phone']));
$message = strip_tags(htmlspecialchars($_POST['message']));
// Create the email and send the message
$to = 'maxmaxstudio2#gmail.com'; // Add your email address inbetween the '' replacing yourname#yourdomain.com - This is where the form will send a message to.
$email_subject = "Website Contact Form: $name";
$email_body = "Vous avez recu un nouveau message\n\n"."Voici les détails:\n\nName: $name\n\nEmail: $email_address\n
\nPhone: $phone\n\nMessage:\n$message\n\nThe client want help in these days: $time\n";
$headers = "From: maxmaxstudio2#gmail.com\n"; // This is the email address the generated message will be from. We recommend using something like noreply#yourdomain.com.
$headers .= "Reply-To: $email_address";
mail($to,$email_subject,$email_body,$headers);
return true;
?>
Try this
<?php
foreach($_POST['time'] as $value)
{
echo 'checked: '.$value.'';
// insert your email code here
}
?>
Ok I found it ! :)
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$message = $_POST['message'];
$time = nl2br(implode(',', $_POST['time']));
$to = 'maxmaxstudio2#gmail.com'; // Add your email address inbetween the '' replacing yourname#yourdomain.com - This is where the form will send a message to.
$email_subject = "Demande d'aide-ménagère: $name";
$email_body =
"Vous avez recu un nouveau message de:$name\n
\n"."Voici les détails:\n
Nom: $name\n
Email: $email\n
Téléphone: $phone\n
Message:\n$message\n
\nThe client want help in these days: $time";
$headers = "From: maxmaxstudio2#gmail.com\n"; // This is the email address the generated message will be from. We recommend using something like noreply#yourdomain.com.
$headers .= "Reply-To: $email";
mail($to,$email_subject,$email_body,$headers);
?>
The solution was $time = nl2br(implode(',', $_POST['time']));
Found it Here
I'm new to PHP and have a problem with the following contact form:
The variable: $empresa = $_POST['empresa']; is not working... and I don't understand where the problem is. When I try to use it in the E-Mail sent, it just doesn't show up.
$received_subject = 'Has sido contactado desde www.company.com por ' . $name . '. Empresa' . $empresa . '.' ;
**This is the PHP I'm using: **
THANKS in advance
<?php
if(!$_POST) exit;
function isEmail($email) {
return(preg_match("/^[-_.[:alnum:]]+#((([[:alnum:]]|[[:alnum:]][[:alnum:]-]*[[:alnum:]])\.)+(ad|ae|aero|af|ag|ai|al|am|an|ao|aq|ar|arpa|as|at|au|aw|az|ba|bb|bd|be|bf|bg|bh|bi|biz|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|com|coop|cr|cs|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|edu|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gh|gi|gl|gm|gn|gov|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|in|info|int|io|iq|ir|is|it|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|me|mg|mh|mil|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|museum|mv|mw|mx|my|mz|na|name|nc|ne|net|nf|ng|ni|nl|no|np|nr|nt|nu|nz|om|org|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|pro|ps|pt|pw|py|qa|re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)$|(([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5])\.){3}([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5]))$/i",$email));
}
if (!defined("PHP_EOL")) define("PHP_EOL", "\r\n");
$name = $_POST['name'];
$empresa = $_POST['empresa'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$comments = $_POST['comments'];
if(trim($comments) == '') {
echo '<div class="error_message">Has olvidado escribir tu mensaje.</div>';
exit();
}
if(trim($name) == '') {
echo '<div class="error_message">Tienes que poner un nombre.</div>';
exit();
} else if(trim($email) == '') {
echo '<div class="error_message">Por favor pon tu dirección de e-mail, para poder ponernos en contacto contigo.</div>';
exit();
} else if(!isEmail($email)) {
echo '<div class="error_message">Dirección de e-mail inválida, inténtelo nuevamente.</div>';
exit();
}
$address = "mail#mail.com";
$received_subject = 'Has sido contactado desde www.company.com por ' . $name . '. Empresa' . $empresa . '.' ;
$received_body = "$name te ha contactado desde www.company.com " . PHP_EOL . PHP_EOL;
$received_content = "\"$comments\"" . PHP_EOL . PHP_EOL;
$received_reply = "Responder a $name $email o llamar al teléfono: $phone | Empresa: $empresa ";
$message = wordwrap( $received_body . $received_content . $received_reply, 100 );
$header = "From: $email" . PHP_EOL;
$header .= "Reply-To: $email" . PHP_EOL;
if(mail($address, $received_subject, $message, $header)) {
// Email has sent successfully, echo a success page.
echo "<h2>E-Mail enviado con éxito</h2>";
echo "<p>Gracias <strong>$name</strong>, tu mensaje ha sido enviado.</p>";
} else {
echo 'ERROR!';
}
MY form is here:
<form method="post" action="contact.php" name="contactform" id="contactform">
<fieldset id="contact_form">
<label for="name">
<input type="text" name="name" id="name" placeholder="Nombre *">
</label>
<label for="empresa">
<input type="text" name="empresa" id="empresa" placeholder="Empresa *">
</label>
<label for="email">
<input type="email" name="email" id="email" placeholder="E-Mail *">
</label>
<label for="phone">
<input type="text" name="phone" id="phone" placeholder="Número de teléfono">
</label>
<label for="comments">
<textarea name="comments" id="comments" placeholder="Mensaje *"></textarea>
</label>
<p class="obligatorio"> * = Obligatorio</p>
<input type="submit" class="submit btn btn-default btn-black" id="submit" value="Enviar">
</fieldset>
</form>
If all of your other post variables are working then it sounds like the $_POST['empresa'] variable is not making it to the php page. To debug your script you can either switch your form method to GET to see the query string in the browser url or use a tool like firebug which is a add on for firefox. You will get error on your php page when you switch to the GET method on your html form. Don't worry about that your are just trying to see if the empressa variable is being sent via the http Post request.
Ok your variable dump should show this based on the code your provided
array
'name' => string 'Larry' (length=5)
'empresa' => string 'Lane' (length=4)
'email' => string 'ok#yahoo.com' (length=12)
'phone' => string '123' (length=3)
'comments' => string 'ok' (length=2)
So empresa is making it to the page just fine. I did notice that you do not have an opening form tag for your form? You should have something like this with the names of your file in place of the ones I used for testing of course.
<form name="testform" action="testingpostvariables.php" method="POST">
Place echo $message; after your line of code in your php file
$message = wordwrap( $received_body . $received_content . $received_reply, 100 );
$echo message;
When I did it empresa showed up.
Ok put this code in seperate php file and test it so we can figure out why "empresa" is not showing up. I would also trying refreshing your browser before testing this file to make sure there is no bad cached results.
<form method="post" action="contact.php" name="contactform" id="contactform">
<fieldset id="contact_form">
<label for="name">
<input type="text" name="name" id="name" placeholder="Nombre *">
</label>
<label for="empresa">
<input type="text" name="empresa" id="empresa" placeholder="Empresa *">
</label>
<label for="email">
<input type="email" name="email" id="email" placeholder="E-Mail *">
</label>
<label for="phone">
<input type="text" name="phone" id="phone" placeholder="Número de teléfono">
</label>
<label for="comments">
<textarea name="comments" id="comments" placeholder="Mensaje *"></textarea>
</label>
<p class="obligatorio"> * = Obligatorio</p>
<input type="submit" class="submit btn btn-default btn-black" id="submit" value="Enviar">
</fieldset>
</form>
<?php
//debug
echo var_dump($_POST);
//debug
if(!$_POST){
echo "NO POST";
//exit;
}
else{
echo "POSTED";
}
function isEmail($email) {
return(preg_match("/^[-_.[:alnum:]]+#((([[:alnum:]]|[[:alnum:]][[:alnum:]-]*[[:alnum:]])\.)+(ad|ae|aero|af|ag|ai|al|am|an|ao|aq|ar|arpa|as|at|au|aw|az|ba|bb|bd|be|bf|bg|bh|bi|biz|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|com|coop|cr|cs|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|edu|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gh|gi|gl|gm|gn|gov|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|in|info|int|io|iq|ir|is|it|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|me|mg|mh|mil|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|museum|mv|mw|mx|my|mz|na|name|nc|ne|net|nf|ng|ni|nl|no|np|nr|nt|nu|nz|om|org|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|pro|ps|pt|pw|py|qa|re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)$|(([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5])\.){3}([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5]))$/i",$email));
}
if (!defined("PHP_EOL")) define("PHP_EOL", "\r\n");
$name = $_POST['name'];
$empresa = $_POST['empresa'];
//impress is posting just fine
$email = $_POST['email'];
$phone = $_POST['phone'];
$comments = $_POST['comments'];
if(trim($comments) == '') {
echo '<div class="error_message">Has olvidado escribir tu mensaje.</div>';
exit();
}
if(trim($name) == '') {
echo '<div class="error_message">Tienes que poner un nombre.</div>';
exit();
} else if(trim($email) == '') {
echo '<div class="error_message">Por favor pon tu dirección de e-mail, para poder ponernos en contacto contigo.</div>';
exit();
} else if(!isEmail($email)) {
echo '<div class="error_message">Dirección de e-mail inválida, inténtelo nuevamente.</div>';
exit();
}
$address = "mail#mail.com";
$received_subject = 'Has sido contactado desde www.company.com por ' . $name . '. Empresa' . $empresa . '.' ;
//debug
//$empressa is still working fine
$received_body = "$name te ha contactado desde www.company.com " . PHP_EOL . PHP_EOL;
$received_content = "\"$comments\"" . PHP_EOL . PHP_EOL;
$received_reply = "Responder a $name $email o llamar al teléfono: $phone | Empresa: $empresa ";
$message = wordwrap( $received_body . $received_content . $received_reply, 100 );
echo $message;
$header = "From: $email" . PHP_EOL;
$header .= "Reply-To: $email" . PHP_EOL;
/*
if(mail($address, $received_subject, $message, $header)) {
// Email has sent successfully, echo a success page.
echo "<h2>E-Mail enviado con éxito</h2>";
echo "<p>Gracias <strong>$name</strong>, tu mensaje ha sido enviado.</p>";
} else {
echo 'ERROR!';
}
*/
This what my result looked like with the empresa value at the end(Lane is the empresa value I entered in the form).
POSTEDLarry te ha contactado desde www.company.com "This is a really long message ok lets see whats going on with this php code it is not sending the empresa variable" Responder a Larry mail#mail.com o llamar al teléfono: 12345678 | Empresa: Lane
Ok in your "custom.js" file you have the following line of code that could be causing some problems.
$.post(action, {
name: $('#name').val(),
empresa: $('#empresa').val(),
email: $('#email').val(),
phone: $('#phone').val(),
comments: $('#comments').val(), //remove this comma
There should not be a comma after the last property value try removing that to see if you get the value of empresa from the jquery code. Try it and let me know i
I've solved the issue, by changing the word empresa with something else.
I think there was some sort of collision using this word.
Thanks so much for your help!