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. :-)
Related
I have a completely functional Form that sends mail as it should and all BUT for some reason, when I (try to) submit my message, instead of showing the success or error alert under the form, it opens the sendmail.php page with the messages, without any CSS... It's been 4 days and I'm going crazy. I'm sure it's actually a stupid typo or something but I can't find it, please help.
Screen of the "Success/Alert" display
Here's my sendmail.php:
<?php
$sendto = 'my#email.com';
$subject = 'Message de votre site';
$errormessage = 'Ah, vous avez oublié quelques informations. Réessayez ? ';
$thanks = "Merci pour votre message ! On vous répond aussi vite que possible. ";
$honeypot = "Vous êtes tombé dans le piège ! Si vous êtes humain.e, recommencez ! ";
$emptyname = 'Quel est votre nom ? ';
$emptyemail = 'Quelle est votre adresse mail ? ';
$emptymessage = 'Et votre message ? ';
$alertname = 'Utilisez uniquement un alphabet standard. ';
$alertemail = 'Entrez ce format de mail : <i>name#example.com</i>. ';
$alertmessage = "Vérifiez que vous n 'avez utilisé aucun caractère spécial. ";
$alert = '';
$pass = 0;
function clean_var($variable) {
$variable = strip_tags(stripslashes(trim(rtrim($variable))));
return $variable;
}
if ( empty($_REQUEST['last']) ) {
if ( empty($_REQUEST['name']) ) {
$pass = 1;
$alert .= "<li>" . $emptyname . "</li>";
$alert .= "<script>jQuery(\"#name\").addClass(\"error\");</script>";
} elseif ( preg_match( "/[][{}()*+?.\\^$|]/", $_REQUEST['name'] ) ) {
$pass = 1;
$alert .= "<li>" . $alertname . "</li>";
}
if ( empty($_REQUEST['email']) ) {
$pass = 1;
$alert .= "<li>" . $emptyemail . "</li>";
$alert .= "<script>jQuery(\"#email\").addClass(\"error\");</script>";
} elseif ( !preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/", $_REQUEST['email']) ) {
$pass = 1;
$alert .= "<li>" . $alertemail . "</li>";
}
if ( empty($_REQUEST['message']) ) {
$pass = 1;
$alert .= "<li>" . $emptymessage . "</li>";
$alert .= "<script>jQuery(\"#message\").addClass(\"error\");</script>";
} elseif ( preg_match( "/[][{}()*+?\\^$|]/", $_REQUEST['message'] ) ) {
$pass = 1;
$alert .= "<li>" . $alertmessage . "</li>";
}
if ( $pass==1 ) {
echo "<script>$(\".result\").toggle();$(\".result\").toggle().hide(\"fast\").show(\"fast\"); </script>";
echo "<script>$(\".result .alert\").addClass('alert-danger').removeClass('alert-success'); </script>";
echo $errormessage;
echo $alert;
} elseif (isset($_REQUEST['message'])) {
$message = "From: " . clean_var($_REQUEST['name']) . "\n";
$message .= "Email: " . clean_var($_REQUEST['email']) . "\n";
$message .= "Message: \n" . clean_var($_REQUEST['message']);
$header = 'From:'. clean_var($_REQUEST['email']);
mail($sendto, $subject, $message, $header);
echo "<script>$(\".result\").toggle();$(\".result\").toggle().hide(\"fast\").show(\"fast\");$('#contactForm')[0].reset();</script>";
echo "<script>$(\".result .alert\").addClass('alert-success').removeClass('alert-danger'); </script>";
echo $thanks;
echo "<script>jQuery(\"#name\").removeClass(\"error\");jQuery(\"#email\").removeClass(\"error\");jQuery(\"#message\").removeClass(\"error\");</script>";
echo "<script>$(\".result .alert\").delay(4000).hide(\"fast\");</script>";
die();
echo "<br/><br/>" . $message;
}
} else {
echo "<script>$(\".result\").toggle();$(\".result\").toggle().hide(\"fast\").show(\"fast\");</script>";
echo $honeypot;
}
?>
And HTML:
<form class="form-inline flowuplabels" role="form" method="post" autocomplete="off" id="contactForm" action="js/sendmail.php">
<div class="form-group fl_wrap">
<label class="fl_label" for="name">Nom :</label>
<input type="text" name="name" value="" id="name" class="form-control fl_input" required>
</div>
<div class="form-group fl_wrap">
<label class="fl_label" for="email">Email :</label>
<input type="text" name="email" value="" id="email" class="form-control fl_input" required>
</div>
<span class="form-group fl_wrap honeypot">
<label class="fl_label" for="last">Honeypot:</label>
<input type="text" name="last" value="" id="last" class="form-control fl_input">
</span>
<div class="form-group fl_wrap">
<label class="fl_label" for="message">Message :</label>
<textarea type="text" name="message" value="" id="message" class="materialize-textarea" required></textarea>
</div>
<div class="form-group">
<button type="submit" value="Send" id="submit" class="btn btn-block">Envoyer</button>
</div>
<div id="form-alert" class="form-group">
<div class="result">
<div class="alert"></div>
</div>
</div>
</form>
As some asked. The HTML is on the index page and the sendmail.php is an independent page.
And this is where the success/alert message is supposed to appear :
Form in website
I'm making an app with ionic 2 angular 2, and I have made a mailform in php. Now how can I make my app use my php file to send the mailform?
this is my html
<ion-header>
<ion-navbar>
<ion-title>Mail</ion-title>
</ion-navbar>
</ion-header>
<ion-content padding>
<ion-list>
<form id="mailform" action="mailform.php" method="post">
<ion-item>
<ion-input type="text" id="naam" placeholder="Naam" required="required" pattern="\D*"></ion-input>
</ion-item>
<ion-item>
<ion-input type="text" id="voornaam" placeholder="Voornaam" required="required" pattern="\D*"></ion-input>
</ion-item>
<ion-item>
<ion-input type="text" id="email" placeholder="Email" required="required" pattern="^[a-zA-Z0-9_.+-]+#[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$"> </ion-input>
</ion-item>
<ion-item>
<ion-select placeholder="Onderwerp" required="required">
<ion-option id="Bug">Bug</ion-option>
<ion-option id="FouteInfo">Foute info</ion-option>
</ion-select>
</ion-item>
<ion-item>
<textarea id="text" id="text" type="text" rows="5" placeholder="Vertel ons het probleem" required="required"></textarea>
</ion-item>
<a (click)="send()" ion-button color="primary" icon-left>
<ion-icon name="at" (click)="send"></ion-icon>
Verstuur
</a>
</form>
</ion-list>
</ion-content>
this is my php file
<ion-header>
<ion-navbar>
<ion-title>Mail</ion-title>
</ion-navbar>
</ion-header>
<ion-content padding>
<?php
$ok = false;
if (preg_match("/\D*/", $_POST["naam"])){
$naam = true;
}
else {
echo "Naam niet goed <br/>";
}
if (preg_match("/\D*/", $_POST["voornaam"])){
$voornaam = true;
}
else {
echo "Voornaam niet goed <br/>";
}
if(isset($_POST['bug'])){
$bug = true;
}
else {
$bug = false;
}
if(isset($_POST['fouteInfo'])){
$fouteInfo = true;
}
else {
$fouteInfo = false;
}
if (preg_match("/^[a-zA-Z0-9_.+-]+#[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$/", $_POST["email"])){
$email = true;
}
else {
echo "email adres niet correct <br/>"
}
if (!empty($_POST["text"])){
$text = true;
}
else {
echo "text invullen aub <br/>";
}
if ($naam && $voornaam && $email && $text && ($bug || $fouteInfo)) {
$ok = true;
}
//Bericht voor admin
$to = "anthony.gesquiere#student.vives.be";
//$to = $_POST['email'];
if($bug){
$subject = "Bug";
}
else {
$subject = "Foute Info";
}
$message = "Naam: " . $_POST['naam'] . $_POST['voornaam'] . "<br/> Email: " . $_POST['email'] . "<br /> Bericht: " . $_POST['text'];
$header = "From: Stad Kortrijk <noreply#kortrijk.be> \r\n";
$header .= "MIME-Version: 1.0\r\n";
$header .= "Content-type: text/html\r\n";
$retvalAdmin = mail($to,$subject,$message,$header);
//Bericht voor gebruiker
$to = $_POST['email'];
$subject = "Bedankt voor uw melding";
$message ="<h1>Bedankt ". $_POST['naam'] . " " . $_POST['voornaam'] . " </h1> <br/><br> We zullen dit probleem zo spoedig mogelijk trachten op te lossen <br>Met vriendelijke groeten <br> Stad Kortrijk <br/>";
$header = "From: Stad Kortrijk <noreply#kortrijk.be> \r\n";
$header .= "MIME-Version: 1.0\r\n";
$header .= "Content-type: text/html\r\n";
$retval = mail($to,$subject,$message,$header);
if( $retval == true )
{
echo "Bedankt voor uw aanvraag";
}
else
{
echo "Er is een fout opgetreden, uw aanvraag werd niet verstuurd, excuses voor dit ongemak. ";
}
}
else {
var_dump($_POST);
}
?>
</ion-content>
Now how do I make this work so that my app sends a http post request to my server where my php file is running, so that it sends the mailform?
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!
I'm quite new to php and am trying to make a simple form that mails the form-data to a specified mail address. I used this script here and modified it to my needs but when I try it out it just does nothing. It will go to the php page but nothing else happens and the page is empty.
Here is my HTML form:
<form class="contact" name="contact" method="post" action="./files/php/contact_send.php">
<table id="form">
<tr>
<td class="data-right"><label for="naam"><b>NAAM</b></label></td>
<td class="data-left">
<input type="text" name="naam" size="50" style="border-style:inset"/>
</td>
</tr>
<tr>
<td class="data-right"><label for="mailadres"><b>E-MAILADRES</b></label></td>
<td class="data-left">
<input type="text" name="mailadres" size="50" style="border-style:inset"/>
</td>
</tr>
<tr>
<td class="data-right"><label for="boodschap"><b>BOODSCHAP</b></label></td>
<td class="data-left">
<textarea name="boodschap" cols="39" rows="4" style="border-style:inset"></textarea>
</td>
</tr>
</table>
<input type="image" src="./files/img/stuur.png"
onmouseover="this.src='./files/img/stuur-hover.png'"
onmouseout="this.src='./files/img/stuur.png'"
alt="Stuur" width="150px" name="submit" value="Submit" />
</form>
and my php code:
<?php
if(isset($_POST['mailadres'])) {
// CHANGE THE TWO LINES BELOW
$email_to = "blabla#gmail.com";
$email_subject = "Contact";
function died($error) {
// your error code can go here
echo "Het spijt ons maar er is iets fout gelopen bij het versturen van het formulier";
echo "Hieronder zijn de fouten weergegeven:<br /><br />";
echo $error."<br /><br />";
echo "Verbeter de fouten en probeer opnieuw.<br /><br />";
die();
}
// validation expected data exists
if(!isset($_POST['naam']) ||
!isset($_POST['mailadres']) ||
!isset($_POST['boodschap'])) {
died('Het spijt ons maar het lijkt er op dat er iets mis is gelopen met de gegevens die u heeft ingevuld.');
}
$naam = $_POST['naam']; // required
$mailadres = $_POST['mailadres']; // required
$boodschap = $_POST['boodschap']; // required
$error_message = "";
$email_exp = '/^[A-Za-z0-9._%-]+#[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';
if(!preg_match($email_exp,$mailadres)) {
$error_message .= 'Het e-mailadres dat u heeft opgegeven is geen geldig e-mailadres.<br />';
}
$naam_exp = "/^[A-Za-z .'-]+$/";
if(!preg_match($naam_exp,$naam)) {
$error_message .= 'De naam die u heeft opgegeven is geen geldige naam.<br />';
}
if(strlen($boodschap) < 5) {
$error_message .= 'De opgegeven boodschap is niet lang genoeg, gelieve minstens 5 letters te gebruiken.<br />';
}
if(strlen($error_message) > 0) {
died($error_message);
}
$email_message = "Formulier details:\n\n";
function clean_string($string) {
$bad = array("content-type","bcc:","to:","cc:","href");
return str_replace($bad,"",$string);
}
$email_message .= "Naam: ".clean_string($naam)."\n";
$email_message .= "E-mail: ".clean_string($mailadres)."\n";
$email_message .= "Boodschap: ".clean_string($boodschap)."\n";
// create email headers
$headers = 'From: '.$mailadres."\r\n".'Reply-To: '.$mailadres."\r\n" .'X-Mailer: PHP/' phpversion();
#mail($email_to, $email_subject, $email_message, $headers);
?>
Bedankt om ons te contacteren. We proberen zo spoedig mogelijk met u contact op te nemen.
<?php
}
die();
?>
You have a syntax error at this line:
$headers = 'From: '.$mailadres."\r\n".'Reply-To: '.$mailadres."\r\n" .'X-Mailer: PHP/' phpversion();
You forgot a dot in your string concatination at phpversion(). Change it to:
$headers = 'From: '.$mailadres."\r\n".'Reply-To: '.$mailadres."\r\n" .'X-Mailer: PHP/'. phpversion();
The reason why you got an empty screen is because php is probably not displaying the error. This is a security measure. You can force php to report and display the errors by adding the next lines to the top of your script:
<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
?>
You should remove these lines in a production environment because it is a security risk.
Replace:
if(!isset($_POST['naam']) ||
!isset($_POST['mailadres']) ||
!isset($_POST['boodschap'])) {
died('Het spijt ons maar het lijkt er op dat er iets mis is gelopen met de gegevens die u heeft ingevuld.');
}
with:
if ( (!isset($_POST['naam'])) ||
(!isset($_POST['mailadres'])) ||
(!isset($_POST['boodschap'])) ) {
died('Het spijt ons maar het lijkt er op dat er iets mis is gelopen met de gegevens die u heeft ingevuld.');
}
You were missing a lot of brackets for this statement.
Also, change the bottom part from:
?>
Bedankt om ons te contacteren. We proberen zo spoedig mogelijk met u contact op te nemen.
<?php
}
die();
?>
To:
echo "Bedankt om ons te contacteren. We proberen zo spoedig mogelijk met u contact op te nemen.";
}
die();
?>
I have a PHP script which is working absolutely fine in Firefox, but when i use Internet Explorer, the session variables won't work.
I'm using Internet Explorer version 9.0.8.
Here's the script. Who can help?
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<?php
session_start();
ob_flush();
?>
<html>
<head>
<title>Neem contact op</title>
<style type="text/css">
label,a, body
{
font-family : Arial, Helvetica, sans-serif;
font-size : 11px;
}
</style>
</head>
<body>
<?php
if(isset($_POST['submit'])){
$naam = $_POST['naam'];
$email = $_POST['email'];
$domeinnaam = $_POST['domeinnaam'];
$opmerking = $_POST['opmerking'];
$code = $_POST['captcha'];
if($naam == "" || $email == "" || $opmerking == ""){
echo "<font color='red'>Je hebt niet alle verplichte velden ingevuld!</font>";
} else{
if($code != $_SESSION['code']){
echo "<font color='red'>De captcha code is onjuist overgenomen!</font>";
} else{
if(!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email)){
echo "<font color='red'>Je hebt een ongeldig e-mail adres ingevuld!</font>";
} elseif(isset($_SESSION['tijd']) && $_SESSION['tijd'] > time() ){
$tijdover = $_SESSION['tijd'] - time();
echo "<font color='red'>Je moet nog ". $tijdover ." seconden wachten om een nieuw bericht in te sturen!</font>";
} else{
$_SESSION['tijd'] = time() + 60;
$headers = "From: ". $email ."\r\nContent-type: text/html";
$body = "<html>
<body>
Er is een nieuw bericht gestuurd via de contact pagina.<br /><br />
Naam: ". $naam ."<br />E-mail: ". $email ."<br />Domeinnaam: ". $domeinnaam ."<br /><br />Opmerking: <br /><br />". $opmerking."
</body>
</html>";
$mail = mail("testmail#gmail.com", "Contact - " . $email . " - " . $domeinnaam, $body, $headers);
if( $mail ){
echo "<font color='green'>Bedankt voor uw bericht, wij proberen zo spoedig mogelijk je e-mail te beantwoorden.</font>";
}else{
echo "<font color='red'>Er is iets fout gegaan tijdens e-mailen, probeer het later nog eens opnieuw!</font>";
}
}
}
}
}
?>
<form method="POST" name="contact_form" action="contact.php">
<p>
<label for='name'>Naam: (verplicht) </label><br>
<input type="text" name="naam" value=''>
</p>
<p>
<label for='email'>Email: (verplicht) </label><br>
<input type="text" name="email" value=''>
</p>
<p>
<label for='email'>Domeinnaam: </label><br>
<input type="text" name="domeinnaam" value=''>
</p>
<p>
<label for='message'>Opmerking: (verplicht) </label> <br>
<textarea name="opmerking" rows=8 cols=30></textarea>
</p>
<p>
<span style="font-size: 14px;">
<?php
$random = rand(1000, 9999);
$_SESSION['code'] = $random;
echo $random;
?>
</span>
<br />
<label for='message'>Typ de code hierboven over:</label><br>
<input name="captcha" type="text"><br>
</p>
<input type="submit" value="Verstuur" name='submit'>
</form>
</body>
</html>
Session needs to be opened before anything else is displayed. That is your cause.
can you try
<?php
session_start();
ob_flush();
?>
before
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
Verify your domain name do not contain: "_" or "-"
You could find information about that issue in the next links:
https://support.microsoft.com/en-us/kb/316112
https://blogs.msdn.microsoft.com/ieinternals/2009/08/20/internet-explorer-cookie-internals-faq/