PHP Mail Function 404 Error [duplicate] - php

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! :)

Related

How to send a email with attachments with php email [duplicate]

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.

"charset=UTF-8" sending mail in php

My teacher asked us to be able to send email via our website. As I speak french, I tried using charset=UTF-8 in the header. It works well for mail address, headers, name with special char but not for the message of the mail itself...
I always receive message like =?UTF-8?B?w6nDqSDDqMOoIMOgw6Agw6fDpw==?= .
Here is my php codes :
function contenuContactHTML(){
echo ' <div id="contenu">
<h1> Formulaire de Contact </h1>
<form action="" method="post">
Votre Nom: <input type="text" name="prenomFormulaire"><br>
Votre E-mail: <input type="text" name="emailFormulaire"><br>
Sujet du message : <input type="text" name="sujetMailFormulaire"><br>
Votre Message: <textarea cols="40" rows="6" name="messageFormulaire" maxlength="4000" placeholder="message limité à 4000 cractères" required></textarea><br />
<input type="submit" name="envoieMailContact" value="Envoyer E-Mail">
</form>
</div><!-- #contenu -->
</div><!-- #centre --> ';
envoieMail();
}
function envoieMail(){
if(isset($_POST['envoieMailContact'])){
$a = <i> My email adress</i>;
$sujet = "=?UTF-8?B?".base64_encode($_POST['sujetMailFormulaire'])."?=";
$de = "=?UTF-8?B?".base64_encode($_POST['emailFormulaire'])."?=";
$messFormulaire = $_POST['messageFormulaire'];
$message = "=?UTF-8?B?" . base64_encode($messFormulaire) . "?=";
$entete = "From: ". $de ."\r\n"
."MIME-Version: 1.0" . "\r\n"
.'Content-type: text/html; charset=UTF-8' .'\r\n';
mail($a, $sujet, $message, $entete);
echo "<script language='JavaScript'>alert('Message envoyé !')</script>";
}
}
Here is an example of the mail i receive :
email adresse : mické#hotmail.com
sujet (header) : on é pas des pigeaôns
content of the mail (message) :
=?UTF-8?B?YXplcnR5dWlvcF4kDQpxc2RmZ2hqa2xtw7nCtQ0Kd3hjdmJuLDs6DQrCsibDqSInKMKnw6ghw6fDoCkt?=

Field in contact form

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!

Contact PHP file not loading on Submit

Got this HTML contact form:
<form action="contact.php" method="get">
Nombre<br>
<input type="text" name="cf_name"><br>
Email<br>
<input type="text" name="cf_email"><br>
Mensaje<br>
<textarea name="cf_message"> </textarea><br>
<input type="submit" value="Enviar">
</form>
And a separate php file sending contact info:
$mail_to = 'tienda#shambricolage.com';
$subject = 'Mensaje de Contacto de Sham Bricolage - '.$field_name;
$body_message = 'Persona de contacto: '.$field_name."\n";
$body_message .= 'E-mail de contacto: '.$field_email."\n";
$body_message .= 'Mensaje: '.$field_message;
$headers = 'De: '.$field_email."\r\n";
$headers .= 'Responder a: '.$field_email."\r\n";
$mail_status = mail($mail_to, $subject, $body_message, $headers);
if ($mail_status) { ?>
<script language="javascript" type="text/javascript">
alert('Gracias por su mensaje');
window.location = 'contacto.html';
</script>
<?php
}
else { ?>
<script language="javascript" type="text/javascript">
alert('No se pudo enviar. Por favor, contacte por email a tienda#shambricolage.com');
window.location = 'contacto.html';
</script>
<?php
}
?>
On form submit, page does not load and web keeps loading with no email sending at all. You can check this on http://www.shambricolage.com/Contacto.html when submiting form, nothing loads.
Done on a tool called Webpage Maker
I've changed a bit. Dont know if it works. But its messed up and not well programmed.
HTML:
<form action="contact.php" method="GET">
Nombre<br>
<input type="text" name="cf_name"><br>
Email<br>
<input type="text" name="cf_email"><br>
Mensaje<br>
<textarea name="cf_message"> </textarea><br>
<input type="submit" value="Enviar">
</form>
PHP:
ob_start();
$field_name = $_GET['cf_name'];
$field_email = $_GET['cf_email'];
$field_message = $_GET['cf_message'];
$mail_to = 'tienda#shambricolage.com';
$subject = 'Mensaje de Contacto de Sham Bricolage - '.$field_name;
$body_message = 'Persona de contacto: '.$field_name."\n";
$body_message .= 'E-mail de contacto: '.$field_email."\n";
$body_message .= 'Mensaje: '.$field_message;
$headers = 'De: '.$field_email."\r\n";
$headers .= 'Responder a: '.$field_email."\r\n";
$mail_status = mail($mail_to, $subject, $body_message, $headers);
if ($mail_status) { ?>
<script language="javascript" type="text/javascript">
alert('Gracias por su mensaje');
</script>
<?php
header('Location: contacto.html');
}
else { ?>
<script language="javascript" type="text/javascript">
alert('No se pudo enviar. Por favor, contacte por email a tienda#shambricolage.com');
</script>
<?php
header('Location: contacto.html');
}
?>
Finally, after contacting hosting team, it was an STMP server and I had to fill a complete PHP mail file with aditional information, as seen on here.
<?php
error_reporting( E_ALL & ~( E_NOTICE | E_STRICT | E_DEPRECATED ) ); //Aquí se genera un control de errores "NO BORRAR NI SUSTITUIR"
require_once "Mail.php"; //Aquí se llama a la función mail "NO BORRAR NI SUSTITUIR"
$field_name = $_POST['cf_name'];
$field_email = $_POST['cf_email'];
$field_message = $_POST['cf_message'];
$to = 'tienda#shambricolage.com'; //Aquí definimos quien recibirá el formulario
$from = 'tienda#shambricolage.com'; //Aquí definimos que cuenta mandará el correo, generalmente perteneciente al mismo dominio
$host = '217.116.0.228'; //Aquí definimos cual es el servidor de correo saliente desde el que se enviaran los correos
$username = 'tienda.shambricolage.com'; //Aqui se define el usuario de la cuenta de correo
$password = '****'; //Aquí se define la contraseña de la cuenta de correo que enviará el mensaje
$subject = 'Mensaje de la tienda Shambricolage'; //Aquí se define el asunto del correo
$body = 'Persona de contacto: '.$field_name."\n";
$body .= 'E-mail de contacto: '.$field_email."\n";
$body .= 'Mensaje: '.$field_message;
$field_name = $_POST['cf_name'];
$field_email = $_POST['cf_email'];
$field_message = $_POST['cf_message'];
$headers = array ('From' => $from,
'To' => $to,
'Subject' => $subject);
$smtp = Mail::factory('smtp',
array ('host' => $host,
'auth' => true,
'username' => $username,
'password' => $password));
$mail = $smtp->send($to, $headers, $body);
if (PEAR::isError($mail)) {
?>
<script language="javascript" type="text/javascript">
alert('No se pudo enviar el mensaje. Por favor, escriba a tienda#shambricolage.com');
window.location = 'index.html';
</script>
<?php
} else {
?>
<script language="javascript" type="text/javascript">
alert('Gracias por su mensaje');
window.location = 'index.html';
</script>
<?php
}
?>

Display form variable on other page with perhaps a session?

Purpose of my code is:
- Validate the form and check for empty fields
- Send e-mail to admin
- Add data to Mysql database
- Show data on result.php
Currently im experiencing problems with showing my data on result.php
quiz.php
<?php
require_once("php/db.php"); /* Database Class */
require_once('php/utils/is_email.php'); /* Email Validation Script */
$contact = new Contact();
/* Class Contact */
class Contact
{
private $db; /* the database obj */
//we have to init $errors array, as otherwise form will produce errors on missing array entry
private $errors = array( /* holds error messages */
'aanhef' => '',
'contactpersoon' => '',
'bedrijfsnaam' => '',
'email' => '',
'telefoon' => '',
'vraag1_antwoorden' => '',
'vraag2_antwoorden' => ''
);
private $has_errors; /* number of errors in submitted form */
public function __construct()
{
$this->db = new DB();
if (!empty($_POST['newcontact'])) {
$this->processNewMessage();
}
}
public function processNewMessage()
{
$aanhef = $_POST['aanhef'];
$contactpersoon = $_POST['contactpersoon'];
$bedrijfsnaam = $_POST['bedrijfsnaam'];
$telefoon = $_POST['telefoon'];
$email = $_POST['email'];
$vraag1_antwoorden = $_POST['vraag1_antwoorden'];
$vraag2_antwoorden = $_POST['vraag2_antwoorden'];
/* Server Side Data Validation */
if (empty($aanhef)) {
$this->setError('aanhef', 'Vul uw aanhef in');
}
if (empty($contactpersoon)) {
$this->setError('contactpersoon', 'Vul uw contactpersoon in');
}
if (empty($bedrijfsnaam)) {
$this->setError('bedrijfsnaam', 'Vul uw bedrijfsnaam in');
}
if (empty($telefoon)) {
$this->setError('telefoon', 'Vul uw telefoon in');
}
if (empty($vraag1_antwoorden)) {
$this->setError('vraag1_antwoorden', 'Selecteer een antwoord a.u.b.');
}
if (empty($vraag2_antwoorden)) {
$this->setError('vraag2_antwoorden', 'Selecteer een antwoord a.u.b.');
}
if (empty($email)) {
$this->setError('email', 'Vul uw e-mail in');
}
/* No errors, insert in db
else*/
if(!$this->has_errors) {
if(($ret = $this->db->dbNewMessage($aanhef, $contactpersoon, $bedrijfsnaam, $email, $telefoon, $vraag1_antwoorden, $vraag2_antwoorden)) > '') {
//$json = array('result' => 1);
if (SEND_EMAIL) {
$this->sendEmail($aanhef,$contactpersoon,$bedrijfsnaam,$email,$telefoon,$vraag1_antwoorden,$vraag2_antwoorden);
//This is for relocating to successful result page
header('Location: result.php');
exit;
} else {
//This will need special treatment. You have to prepare an errorpage
//for database-related issues.
header("Location: database-error.html");
exit;
}
}
}
}
public function sendEmail($aanhef,$contactpersoon,$bedrijfsnaam,$email,$telefoon,$vraag1_antwoorden,$vraag2_antwoorden)
{
/* Just format the email text the way you want ... */
$message_body = "<div style=\"font-size:12px; font-weight:normal;\">Hallo,<br><br>"
."Het volgende bedrijf heeft zich zojuist aangemeld voor de Veiligheids Quiz:</div><br>"
."<table cellpadding=\"1\" cellspacing=\"1\" width=\"550px\"><tr><td style=\"font-size:12px; color:#000000\">Bedrijfsnaam:</td><td style=\"font-size:12px; color:#000000\">".$bedrijfsnaam."</td></tr><tr><td style=\"font-size:12px; color:#000000\">Aanhef:</td><td style=\"font-size:12px; color:#000000\">".$aanhef."</td></tr><tr><td style=\"font-size:12px; color:#000000\">Contactpersoon:</td><td style=\"font-size:12px; color:#000000\">".$contactpersoon."</td></tr><tr><td style=\"font-size:12px; color:#000000\">Telefoonnummer:</td><td style=\"font-size:12px; color:#000000\">".$telefoon."</td></tr><tr><td style=\"font-size:12px; color:#000000\">E-mail:</td><td style=\"font-size:12px; color:#000000\">".$email."</td></tr><tr><td style=\"font-size:12px; color:#000000\">Antwoord vraag 1:</td><td style=\"font-size:12px; color:#000000\">".$vraag1_antwoorden."</td></tr><tr><td style=\"font-size:12px; color:#000000\">Antwoord vraag 2:</td><td style=\"font-size:12px; color:#000000\">".$vraag2_antwoorden."</td></tr></table><br>";
// Geef GELDIGE adressen op
// Een korte benaming voor jouw website
$website_naam = 'Aanmelding Quiz';
// Jouw eigen geldige emailadres
$eigen_emailadres = 'MY MAIL';
// Een geldig emailadres voor errors
$error_emailadres = 'MY MAIL';
// De naam van de verzender
$naam_verzender = ''.$bedrijfsnaam.'';
// Het geldige emailadres van de afzender
$email_verzender = ''.$email.'';
// Een geldig emailadres of helemaal leeg laten
$bcc_emailadres = '';
// HTML mail? True/False
$html = true;
// De headers samenstellen
$headers = 'From: ' . $website_naam . ' <' . $eigen_emailadres . '>' . PHP_EOL;
$headers .= 'Reply-To: ' . $naam_verzender . ' <' . $email_verzender . '>' . PHP_EOL;
$headers .= 'Return-Path: Mail-Error <' . $error_emailadres . '>' . PHP_EOL;
$headers .= ($bcc_emailadres != '') ? 'Bcc: ' . $bcc_emailadres . PHP_EOL : '';
$headers .= 'X-Mailer: PHP/' . phpversion() . PHP_EOL;
$headers .= 'X-Priority: Normal' . PHP_EOL;
$headers .= ($html) ? 'MIME-Version: 1.0' . PHP_EOL : '';
$headers .= ($html) ? 'Content-type: text/html; charset=iso-8859-1' . PHP_EOL : '';
mail(EMAIL_TO,MESSAGE_SUBJECT,$message_body,$headers);
}
public function setError($field, $errmsg)
{
$this->has_errors = true;
$this->errors[$field] = $errmsg;
}
public function errors($field)
{
if (array_key_exists($field,$this->errors)){
return $this->errors[$field];
}
return '';
}
};
?>
<table width="675px" cellpadding="0" cellspacing="0">
<form id="contact_form" method="post" action="">
<label class="label_aanhef" for="aanhef_1"><input name="aanhef" id="aanhef_1" type="radio" value="Dhr." /> Dhr.</label><label class="label_aanhef" for="aanhef_2"><input name="aanhef" id="aanhef_2" type="radio" value="Mevr." /> Mevr.</label>
<span class="error"><?php echo $contact->errors('aanhef'); ?></span>
<input id="contactpersoon" name="contactpersoon" maxlength="120" type="text" onFocus="window.scrollTo(0, 0);"/><span class="error"><?php echo $contact->errors('contactpersoon'); ?></span>
<input id="bedrijfsnaam" name="bedrijfsnaam" maxlength="120" type="text" onFocus="window.scrollTo(0, 0);"/><span class="error"><?php echo $contact->errors('bedrijfsnaam'); ?></span>
<input id="email" name="email" maxlength="120" type="text" onFocus="window.scrollTo(0, 0);"/><span class="error"><?php echo $contact->errors('email'); ?></span>
<input id="telefoon" name="telefoon" maxlength="120" type="text" onFocus="window.scrollTo(0, 0);"/><span class="error"><?php echo $contact->errors('telefoon'); ?></span>
<label class="label_radio" for="vraag1_A"><input name="vraag1_antwoorden" id="vraag1_A" value="A. Dat is helaas fout, het goede antwoord is: C) < 1 Ohm" type="radio" />A) Geen eis</label>
<label class="label_radio" for="vraag1_B"><input name="vraag1_antwoorden" id="vraag1_B" value="B. Dat is helaas fout, het goede antwoord is: C) < 1 Ohm" type="radio" />B) < 0,1 Ohm</label>
<label class="label_radio" for="vraag1_C"><input name="vraag1_antwoorden" id="vraag1_C" value="C. Gefeliciteerd dat is het goede antwoord." type="radio" />C) < 1 Ohm</label>
<label class="label_radio" for="vraag1_D"><input name="vraag1_antwoorden" id="vraag1_D" value="D. Dat is helaas fout, het goede antwoord is: C) < 1 Ohm" type="radio" />D) < 10 Ohm</label>
<span id="vraag1_antwoorden" class="foutmelding_quiz">
<?php echo $contact->errors('vraag1_antwoorden'); ?>
</span>
<label class="label_radio" for="vraag2_A"><input name="vraag2_antwoorden" id="vraag2_A" value="A. Gefeliciteerd dat is het goede antwoord." type="radio" />A) Geen eis</label>
<label class="label_radio" for="vraag2_B"><input name="vraag2_antwoorden" id="vraag2_B" value="B. Dat is helaas fout, het goede antwoord is: A) Geen eis" type="radio" />B) < 0,1 Ohm</label>
<label class="label_radio" for="vraag2_C"><input name="vraag2_antwoorden" id="vraag2_C" value="C. Dat is helaas fout, het goede antwoord is: A) Geen eis" type="radio" />C) < 1 Ohm</label>
<label class="label_radio" for="vraag2_D"><input name="vraag2_antwoorden" id="vraag2_D" value="D. Dat is helaas fout, het goede antwoord is: A) Geen eis" type="radio" />D) < 10 Ohm</label>
<span id="vraag2_antwoorden" class="foutmelding_quiz">
<?php echo $contact->errors('vraag2_antwoorden'); ?>
</span>
<input class="button submit" type="submit" value="" /><input id="newcontact" name="newcontact" type="hidden" value="1"></input>
</form>
Result.php
Aanhef: <?php echo $_POST["aanhef"]; ?><br />
Contactpersoon: <?php echo $_POST["contactpersoon"]; ?><br />
Bedrijfsnaam: <?php echo $_POST["bedrijfsnaam"]; ?><br />
Telefoon: <?php echo $_POST["telefoon"]; ?><br />
E-mail: <?php echo $_POST["email"]; ?><br />
if(!empty($_POST['newcontact'])){
$contact = new Contact();
} else{
//header('Location: result.php');
}
Change it to
$contact = new Contact();
I mean to say : remove condition if() :
Its b'coz when page is not posted it will not create object of class Contact.
Due to this error comes.
You should replace :
if(!empty($_POST['newcontact'])){
$contact = new Contact();
} else{
//header('Location: result.php');
}
By :
$contact = new Contact();
Cause if $_POST['newcontact'] is empty, your $contact object is not set, and the if(!empty($_POST['newcontact'])) is already in your __construct() of Contact
Add something like this to Contact to replace your redirect :
private $display_form = true;
public function getDisplayForm() {
return $this->display_form;
}
And replace :
header('Location: result.php');
exit;
By :
$this->display_form = false;
And below, wrap your HTML like this :
<?php if ($contact->getDisplayForm()) { ?>
<!-- Your Form -->
<table width="675px" cellpadding="0" cellspacing="0">
<form id="contact_form" method="post" action="">
...
</form>
</table>
<?php } else { ?>
<!-- Your Results -->
Aanhef: <?php echo $_POST["aanhef"]; ?><br />
Contactpersoon: <?php echo $_POST["contactpersoon"]; ?><br />
Bedrijfsnaam: <?php echo $_POST["bedrijfsnaam"]; ?><br />
Telefoon: <?php echo $_POST["telefoon"]; ?><br />
E-mail: <?php echo $_POST["email"]; ?><br />
<?php } ?>
Are you sure that $contacts is actually filled?
I see this statement at the beginning of the page:
if(!empty($_POST['newcontact'])){
$contact = new Contact();
} else{
//header('Location: result.php');
}
But no further checks if contacts is actually set. If the POST was empty contacts will be null. Check if contacts is null, and if it is, don't call methods or variables on it. :-)

Categories