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/
Related
I want to know how to add a error or sucess message on the same page, when the user submits a message, with all fields correct.
PS:I am working on localhost and know very little of PHP, so please explain like I'm 5. Thanks
<?php
$errorMSG = "";
// NAME
if (empty($_POST["name"])) {
$errorMSG = "Por favor preencha o seu nome ";
} else {
$name = $_POST["name"];
}
// EMAIL
if (empty($_POST["email"])) {
$errorMSG .= "Por favor preencha com o seu email ";
} else {
$email = $_POST["email"];
}
// MSG SUBJECT
if (empty($_POST["msg_subject"])) {
$errorMSG .= "Por favor escreva um assunto da mensagem";
} else {
$msg_subject = $_POST["msg_subject"];
}
// MESSAGE
if (empty($_POST["message"])) {
$errorMSG .= "Por favor escreva uma mensagem ";
} else {
$message = $_POST["message"];
}
//email here
$EmailTo = "email#hotmail.com";
$Subject = "New Message Received";
//email body text
$Body = "";
$Body .= "Nome: ";
$Body .= $name;
$Body .= "\n";
$Body .= "Email: ";
$Body .= $email;
$Body .= "\n";
$Body .= "Assunto: ";
$Body .= $msg_subject;
$Body .= "\n";
$Body .= "Mensagem: ";
$Body .= $message;
$Body .= "\n";
// send email
$success = mail($EmailTo, $Subject, $Body, "De:".$email);
//success message
if ($success && $errorMSG == ""){
echo "sucesso";
}else{
if($errorMSG == ""){
echo "Algo correu mal :(";
} else {
echo $errorMSG;
}
}
?>
<!DOCTYPE html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Title</title>
<!-- css -->
<link href="css/contactform.css" rel="stylesheet" />
<link href="css/bootstrap.min.css" rel="stylesheet" />
<link href="css/style.css" rel="stylesheet" />
</head>
<body>
<!-- Start Contact Form -->
<form role="form" id="contactForm" class="contact-form" data-toggle="validator" class="shake">
<div class="form-group">
<div class="controls">
<input type="text" id="name" class="form-control" placeholder="Nome" required data-error="Por favor escreva o seu nome">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="form-group">
<div class="controls">
<input type="email" class="email form-control" id="email" placeholder="Email" required data-error="Por favor escreva o seu email">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="form-group">
<div class="controls">
<input type="text" id="msg_subject" class="form-control" placeholder="Assunto" required data-error="Por favor escreva o assunto da mensagem">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="form-group">
<div class="controls">
<textarea id="message" rows="7" placeholder="Mensagem" class="form-control" required data-error="Escreva a sua mensagem"></textarea>
<div class="help-block with-errors"></div>
</div>
</div>
<button type="submit" id="submit" class="btn btn-effect"><i class="fa fa-check"></i>Enviar</button>
<div id="msgSubmit" class="h3 text-center hidden"></div>
<div class="clearfix"></div>
</form>
Also, I configured sendmail's "sendmail.ini" and "php.ini" file so as to test the receiving of emails on my local server, but keep getting this error: Warning: mail(): "sendmail_from" not set in php.ini or custom "From:" header missing in
What's custom "From:"?
Before i explain further, i have to point out that you didn't define or specify action attribute in your form. Your php code in it written form can't work, firstly you have to add action and method attribute to form element like this
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post">
//input element here
</form>
The action attribute point to location of script(PHP file in your case) that will process the form data submitted by the user, but in your case, you want the php itself to process the form data, the $_SERVER["PHP_SELF"] contain the current php file location. For security reason, the php super global "$_SERVER" is wrap inside "htmlspecialchars" function, which escape the spacial characters. Secondly, because your submitting the form to the same php script, you have to check whether the form has been submitted, not when user visit the php page using $_SERVER["REQUEST_METHOD"]. If the REQUEST_METHOD is POST, then the form has been submitted, example:
if ($_SERVER["REQUEST_METHOD"] == "POST") {
//put your validation code here
}
To make it clearer, this is how your php code suppose look like:
<?php
//global variables here
$errorMSG = "";
$name = "";
$email = "";
$msg_subject = "";
$message = "";
$EmailTo = "";
$Subject = "";
$Body = "";
//check if user submitted a form
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// NAME
if (empty($_POST["name"])) {
$errorMSG = "Por favor preencha o seu nome ";
}
else {
$name = $_POST["name"];
}
// EMAIL
if (empty($_POST["email"])) {
$errorMSG .= "Por favor preencha com o seu email ";
}
else {
$email = $_POST["email"];
}
// MSG SUBJECT
if (empty($_POST["msg_subject"])) {
$errorMSG .= "Por favor escreva um assunto da mensagem";
}
else {
$msg_subject = $_POST["msg_subject"];
}
// MESSAGE
if (empty($_POST["message"])) {
$errorMSG .= "Por favor escreva uma mensagem ";
}
else {
$message = $_POST["message"];
}
//email here
$EmailTo = "email#hotmail.com";
$Subject = "New Message Received";
//email body text
$Body = "";
$Body .= "Nome: ";
$Body .= $name;
$Body .= "\n";
$Body .= "Email: ";
$Body .= $email;
$Body .= "\n";
$Body .= "Assunto: ";
$Body .= $msg_subject;
$Body .= "\n";
$Body .= "Mensagem: ";
$Body .= $message;
$Body .= "\n";
// send email
$success = mail($EmailTo, $Subject, $Body, "De:".$email);
//success message
if ($success && $errorMSG == ""){
echo "sucesso";
}
else{
if($errorMSG == ""){
echo "Algo correu mal :(";
}
else {
echo $errorMSG;
}
}
}
?>
I notice that all your input element has no name attribute, which is the name your php script use to access the form data submitted by the user, this is right way to do it:
<input type="text" name="username" placeholder="Enter your name"/>
Another thing you have to take note of, php code execute before the html and JavaScript had a chance.
Don't use this for production php code, for more information on how to correctly do this, visit this website https//www.w3schools.com/php/
you need to add action to your form this way, method and properly submit it.. try this
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
// define variables and set to empty values
$nameErr = $emailErr = "";
$name = $email = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<p><span class="error">* required field.</span></p>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="name" value="<?php echo $name;?>">
<span class="error">* <?php echo $nameErr;?></span>
<br><br>
E-mail: <input type="text" name="email" value="<?php echo $email;?>">
<span class="error">* <?php echo $emailErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
<?php
echo "<h2>Your Input:</h2>";
echo $name;
echo "<br>";
echo $email;
echo "<br>";
?>
</body>
</html>
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 an ASP.NET user, but want to learn PHP, I have made a PHP mail send form and it's made from some tutorials from the net, search by google.
I have one...no two questions.
When I load the page, it send an empty mail to me, why ?
Is there something you will recommend that I use or edit in my code ?
My working code is this
<?php
if (isset($_REQUEST['submitted'])) {
//START of validation
// Initialize error array.
$errors = array();
// Check for a proper name
if (!empty($_REQUEST['navn'])) {
$navn = $_REQUEST['navn'];
$pattern = "/^[a-zA-Z0-9æøåÆØÅ\_]{2,20}/";// This is a regular expression that checks if the name is valid characters
if (preg_match($pattern,$navn)){ $navn = $_REQUEST['navn'];}
else{ $errors[] = 'Dit navn kan kun indholde _, 1-9, A-Z or a-z 2-20 long.';}
}
else {$errors[] = 'Venligst indtast dit navn.';}
//Check for a valid phone number
if (!empty($_REQUEST['telefon'])) {
$telefon = $_REQUEST['telefon'];
$pattern = "/^[0-9\_]{7,20}/";
if (preg_match($pattern,$telefon)){ $telefon = $_REQUEST['telefon'];}
else{ $errors[] = 'Dit telefon nummer kan kun være tal.';}
}
else {$errors[] = 'Venligst indtast dit telefon nummer.';}
// Check for a proper info
if (!empty($_REQUEST['beskrivelse'])) {
$beskrivelse = $_REQUEST['beskrivelse'];
$pattern = "/^[a-zA-Z0-9æøåÆØÅ\_]{2,20}/";// This is a regular expression that checks if the name is valid characters
if (preg_match($pattern,$beskrivelse)){ $beskrivelse = $_REQUEST['beskrivelse'];}
else{ $errors[] = 'Din beskrivelse kan kun indholde _, 1-9, A-Z or a-z 2-20 long.';}
}
else {$errors[] = 'Venligst indtast en beskrivelse.';}
// Check for a proper value
if (!empty($_REQUEST['mvalue'])) {
$mvalue = $_REQUEST['mvalue'];
$pattern = "/^[a-zA-Z0-9æøåÆØÅ\_]{2,20}/";// This is a regular expression that checks if the name is valid characters
if (preg_match($pattern,$mvalue)){ $mvalue = $_REQUEST['mvalue'];}
else{ $errors[] = 'Feltet mængde kan kun indholde _, 1-9, A-Z or a-z 2-20 long.';}
}
else {$errors[] = 'Venligst indtast en mængde.';}
// Check for a proper comment
if (!empty($_REQUEST['kommentar'])) {
$kommentar = $_REQUEST['kommentar'];
$pattern = "/^[a-zA-Z0-9æøåÆØÅ\_]{2,20}/";// This is a regular expression that checks if the name is valid characters
if (preg_match($pattern,$kommentar)){ $kommentar = $_REQUEST['kommentar'];}
else{ $errors[] = 'Din kommentar kan kun indholde _, 1-9, A-Z or a-z 2-20 long.';}
}
else {$errors[] = 'Venligst indtast en kommentar.';}
}
//End of validation
//START Send mail
if (empty($errors)) {
$to = "my#mail.dk";
$message = "<!DOCTYPE HTML>";
$message .= "<html><head></head><body>";
$message .= "<table>";
$message .= "<tr><td colspan='2'>" . $navn . " har sendt denne forespørgsel.</td></tr>";
$message .= "<tr><td>Telefon nr.:</td><td>" . $telefon . "</td></tr>";
$message .= "<tr><td>Beskrivelse:</td><td>" . $beskrivelse . "</td></tr>";
$message .= "<tr><td>Mængde:</td><td>" . $mvalue . "</td></tr>";
$message .= "<tr><td>Kommentar:</td><td>" . $kommentar . "</td></tr>";
$message .= "</table></body></html>";
$message .= trim(stripslashes($message));
$subject = "Mosegården Forespørgsel fra " . $navn . ".";
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type: text/html; charset=utf-8" . "\r\n";
$headers .= "Content-Transfer-Encoding: quoted-printable" . "\r\n";
$headers .= "From: Mosegården Hjemmeside - Forespørgsel" . "\r\n";
mail($to, $subject, $message, $headers);
}
//End of Send mail
?>
<!DOCTYPE html>
<html lang="da">
<head>
<meta charset="utf-8" />
<title></title>
<style>
input[type=text] {
padding:5px; border:2px solid #ccc;
-webkit-border-radius: 5px;
border-radius: 5px;
}
input[type=text]:focus {
border-color:#333;
}
input[type=submit] {
padding:5px 15px;
background:#ccc;
border:0 none;
cursor:pointer;
-webkit-border-radius: 5px;
border-radius: 5px;
}
textarea{
padding:5px; border:2px solid #ccc;
-webkit-border-radius: 5px;
border-radius: 5px;
}
</style>
</head>
<body>
<h1>Forespørgsel</h1>
<div id='emailerror'>
<?php
//Print Errors
if (isset($_REQUEST['submitted'])) {
// Print any error messages.
if (!empty($errors)) {
echo '<hr /><h3>Der skete følgende:</h3><ul>';
// Print each error.
foreach ($errors as $msg) { echo '<li>'. $msg . '</li>';}
echo '</ul><h1>Mail ikke send! pga. følgende fejl.</h1><hr />';
} else {
echo '<hr /><h1 style="color:#00ff00;">Mail Send!</h1><hr />';
}
}
//End of errors array
?>
</div>
<form method="post" action="">
<div>
<div class="input_label user">
<label>Navn:</label>
</div>
<input type="text" name="navn" value="<?php echo $navn; ?>" />
</div>
<br />
<div>
<div class="input_label user">
<label>Telefon nr.:</label>
</div>
<input type="text" name="telefon" value="<?php echo $telefon; ?>" />
</div>
<br />
<div>
<div class="input_label user">
<label>Beskrivelse:</label>
</div>
<textarea name="beskrivelse"><?php echo $beskrivelse; ?></textarea>
</div>
<br />
<div>
<div class="input_label user">
<label>Mængde:</label>
</div>
<input type="text" name="mvalue" value="<?php echo $mvalue; ?>" />
</div>
<br />
<div>
<div class="input_label user">
<label>Kommentar:</label>
</div>
<textarea name="kommentar"><?php echo $kommentar; ?></textarea>
</div>
<br />
<input name="submitted" type="submit" value=" Send " />
</form>
</body>
</html>
Try this. I moved the closing bracket from the if statement on line 2 to the bottom of your send mail routine. See comments on line 78
<?php
if (isset($_REQUEST['submitted'])) {
//START of validation
// Initialize error array.
$errors = array();
// Check for a proper name
if (!empty($_REQUEST['navn'])) {
$navn = $_REQUEST['navn'];
$pattern = "/^[a-zA-Z0-9æøåÆØÅ\_]{2,20}/";// This is a regular expression that checks if the name is valid characters
if (preg_match($pattern,$navn)){ $navn = $_REQUEST['navn'];}
else{ $errors[] = 'Dit navn kan kun indholde _, 1-9, A-Z or a-z 2-20 long.';}
}
else {$errors[] = 'Venligst indtast dit navn.';}
//Check for a valid phone number
if (!empty($_REQUEST['telefon'])) {
$telefon = $_REQUEST['telefon'];
$pattern = "/^[0-9\_]{7,20}/";
if (preg_match($pattern,$telefon)){ $telefon = $_REQUEST['telefon'];}
else{ $errors[] = 'Dit telefon nummer kan kun være tal.';}
}
else {$errors[] = 'Venligst indtast dit telefon nummer.';}
// Check for a proper info
if (!empty($_REQUEST['beskrivelse'])) {
$beskrivelse = $_REQUEST['beskrivelse'];
$pattern = "/^[a-zA-Z0-9æøåÆØÅ\_]{2,20}/";// This is a regular expression that checks if the name is valid characters
if (preg_match($pattern,$beskrivelse)){ $beskrivelse = $_REQUEST['beskrivelse'];}
else{ $errors[] = 'Din beskrivelse kan kun indholde _, 1-9, A-Z or a-z 2-20 long.';}
}
else {$errors[] = 'Venligst indtast en beskrivelse.';}
// Check for a proper value
if (!empty($_REQUEST['mvalue'])) {
$mvalue = $_REQUEST['mvalue'];
$pattern = "/^[a-zA-Z0-9æøåÆØÅ\_]{2,20}/";// This is a regular expression that checks if the name is valid characters
if (preg_match($pattern,$mvalue)){ $mvalue = $_REQUEST['mvalue'];}
else{ $errors[] = 'Feltet mængde kan kun indholde _, 1-9, A-Z or a-z 2-20 long.';}
}
else {$errors[] = 'Venligst indtast en mængde.';}
// Check for a proper comment
if (!empty($_REQUEST['kommentar'])) {
$kommentar = $_REQUEST['kommentar'];
$pattern = "/^[a-zA-Z0-9æøåÆØÅ\_]{2,20}/";// This is a regular expression that checks if the name is valid characters
if (preg_match($pattern,$kommentar)){ $kommentar = $_REQUEST['kommentar'];}
else{ $errors[] = 'Din kommentar kan kun indholde _, 1-9, A-Z or a-z 2-20 long.';}
}
else {$errors[] = 'Venligst indtast en kommentar.';}
//End of validation
//START Send mail
if (empty($errors)) {
$to = "my#mail.dk";
$message = "<!DOCTYPE HTML>";
$message .= "<html><head></head><body>";
$message .= "<table>";
$message .= "<tr><td colspan='2'>" . $navn . " har sendt denne forespørgsel.</td></tr>";
$message .= "<tr><td>Telefon nr.:</td><td>" . $telefon . "</td></tr>";
$message .= "<tr><td>Beskrivelse:</td><td>" . $beskrivelse . "</td></tr>";
$message .= "<tr><td>Mængde:</td><td>" . $mvalue . "</td></tr>";
$message .= "<tr><td>Kommentar:</td><td>" . $kommentar . "</td></tr>";
$message .= "</table></body></html>";
$message .= trim(stripslashes($message));
$subject = "Mosegården Forespørgsel fra " . $navn . ".";
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type: text/html; charset=utf-8" . "\r\n";
$headers .= "Content-Transfer-Encoding: quoted-printable" . "\r\n";
$headers .= "From: Mosegården Hjemmeside - Forespørgsel" . "\r\n";
mail($to, $subject, $message, $headers);
}
//End of Send mail
} // <-- moved bracket to here to close if statement on line 2
?>
<!DOCTYPE html>
<html lang="da">
<head>
<meta charset="utf-8" />
<title></title>
<style>
input[type=text] {
padding:5px; border:2px solid #ccc;
-webkit-border-radius: 5px;
border-radius: 5px;
}
input[type=text]:focus {
border-color:#333;
}
input[type=submit] {
padding:5px 15px;
background:#ccc;
border:0 none;
cursor:pointer;
-webkit-border-radius: 5px;
border-radius: 5px;
}
textarea{
padding:5px; border:2px solid #ccc;
-webkit-border-radius: 5px;
border-radius: 5px;
}
</style>
</head>
<body>
<h1>Forespørgsel</h1>
<div id='emailerror'>
<?php
//Print Errors
if (isset($_REQUEST['submitted'])) {
// Print any error messages.
if (!empty($errors)) {
echo '<hr /><h3>Der skete følgende:</h3><ul>';
// Print each error.
foreach ($errors as $msg) { echo '<li>'. $msg . '</li>';}
echo '</ul><h1>Mail ikke send! pga. følgende fejl.</h1><hr />';
} else {
echo '<hr /><h1 style="color:#00ff00;">Mail Send!</h1><hr />';
}
}
//End of errors array
?>
</div>
<form method="post" action="">
<div>
<div class="input_label user">
<label>Navn:</label>
</div>
<input type="text" name="navn" value="<?php echo $navn; ?>" />
</div>
<br />
<div>
<div class="input_label user">
<label>Telefon nr.:</label>
</div>
<input type="text" name="telefon" value="<?php echo $telefon; ?>" />
</div>
<br />
<div>
<div class="input_label user">
<label>Beskrivelse:</label>
</div>
<textarea name="beskrivelse"><?php echo $beskrivelse; ?></textarea>
</div>
<br />
<div>
<div class="input_label user">
<label>Mængde:</label>
</div>
<input type="text" name="mvalue" value="<?php echo $mvalue; ?>" />
</div>
<br />
<div>
<div class="input_label user">
<label>Kommentar:</label>
</div>
<textarea name="kommentar"><?php echo $kommentar; ?></textarea>
</div>
<br />
<input name="submitted" type="submit" value=" Send " />
</form>
</body>
</html>
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. :-)
I have an issue with the checkboxes to get it working.
If none of the checkboxes have been selected, it gives an errormessage, this works fine!
Also the submitting of all other information.
I just want the form now to submit the checkboxes which have been checked into the confirmationemail. I now only get: array.
The contact.php
<?php
/* Set e-mail recipient */
$myemail = "mukies#gmail.com";
/* Check all form inputs using check_input function */
$yourname = check_input($_POST['yourname'], "Vul uw naam in aub");
$email = check_input($_POST['email']);
$telephone = check_input($_POST['telephone']);
$comments = check_input($_POST['comments'], "Write your comments");
$formCampagne = check_input($_POST['formCampagne']);
foreach($formCampagne as $option) {
print $option."\n";
}
/* If e-mail is not valid show error message */
if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/", $email))
{
show_error("Dit e-mail adres is niet juist, voer een juist e-mailadres in.");
}
/* If telephone is not valid show error message */
if (!preg_match("/[0-9\(\)+.\- ]/s", $telephone))
{
show_error("Voer een juist telefoon nummer in");
}
/* If verification code is not valid show error message */
if (strtolower($_POST['code']) != 'mycode') {die('Voer aub de juiste code in, in hoofdletters.');}
/* If no campaign mode is selected, show error message */
if(empty($formCampagne))
{
show_error ("U heeft geen selectie gemaakt uit de campagne opties, selecteer minimaal een van de opties.");
}
/* Let's prepare the message for the e-mail */
$message = "Hi Rick,
Je hebt weer een offerte aanvraag ontvangen voor Limburg Media! :)
Name: $yourname
E-mail: $email
Telefoon: $telephone
Offerte aanvraag? $formCampagne
Comments: $comments
End of message
";
/* Send the message using mail() function */
mail($myemail, $subject, $message);
/* Redirect visitor to the thank you page */
header('Location: thanks.htm');
exit();
/* Functions we used */
function check_input($data, $problem='')
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
if ($problem && strlen($data) == 0)
{
show_error($problem);
}
return $data;
}
function show_error($myError)
{
?>
<html>
<body>
<b>Gelieve de onderstaande foutmelding door te nemen om uw gegevens correct aan te leveren:</b><br />
<?php echo $myError; ?>
</body>
</html>
<?php exit();}
?> }
The Contact.htm where the visitor fills in his/her form:
<html>
<body>
<p>Benodigde velden zijn <b>vetgedrukt</b>.</p>
<form action="contact.php" method="post">
<p><b>Uw naam:</b> <input type="text" name="yourname" /><br />
<b>E-mail:</b> <input type="text" name="email" /></p>
<b>Telefoonnummer:</b> <input type="text" name="telephone" /></p>
<p>Welk soort campagne wilt u informatie over ?<br />
<input type="checkbox" name="formCampagne[]" value="sandwichborden driehoeksborden" />sandwichborden / driehoeksborden<br />
<input type="checkbox" name="formCampagne[]" value="drukwerk banners" />drukwerk / banners<br />
<input type="checkbox" name="formCampagne[]" value="evenementen outdoor" />outdoor promotie / evenemente<br />
<input type="checkbox" name="formCampagne[]" value="internet website social media" />internet / websites / social media <br />
<input type="checkbox" name="formCampagne[]" value="artwork video" />artwork / videopromotie <br />
<input type="checkbox" name="formCampagne[]" value="promo gadgets sampling" />promoteams / gadgets / sampling <br />
<input type="checkbox" name="formCampagne[]" value="mobiele reclame reclame frames" /> mobiele reclame / reclame frames <br /> </p>
<p><b>Your comments:</b><br />
<textarea name="comments" rows="10" cols="40"></textarea></p>
<p>Validatie code: <input type="text" name="code" /><br />
Vul de tekst <b>MYCODE</b> hierboven in. </p>
<p><input type="submit" value="Send it!"></p>
</form>
</body>
</html>
The thanks.htm page only contains standard text, saying, well... thank you. :)
Can anyone help me out here?
EDIT:
So this would be the correct code ?:
if(isset($formCampagne)) {
echo ".implode(',', $formCampagne)."; // this is the output in the confirmation mail
} else {
echo "U heeft geen selectie gemaakt uit de campagne opties, selecteer minimaal een van de opties.";
But where do I put it? Next to the "Offerte aanvraag?", beacuse this gives an error, as I am in the $message field already.
Sorry I have not yet worked with a isset function yet.
Try replacing
$message = "Hi Rick,
Je hebt weer een offerte aanvraag ontvangen voor Limburg Media! :)
Name: $yourname
E-mail: $email
Telefoon: $telephone
Offerte aanvraag? $formCampagne
Comments: $comments
End of message
";
with:
$message = "Hi Rick,
Je hebt weer een offerte aanvraag ontvangen voor Limburg Media! :)
Name: $yourname
E-mail: $email
Telefoon: $telephone
Offerte aanvraag? ".implode(',', $formCampagne)."
Comments: $comments
End of message
";
Notice that I've changed the plain $formCampagne with implode(',', $formCampagne), 'cause it is actually an array and you have to make it a string if you want to place it in your e-mail message.
Also notice that if none of the checkboxes are selected, $formCampagne will be NULL, so you should also check if isset($formCampagne)
EDIT:
in my example, $formCampagne should actually be $_POST['formCampagne'], I must admit I never used the check_input() function and do not really know how it behaves on arrays.
You could also try to var_dump() the content of both $formCampagne and $_POST['formCampagne']
You can check for isset($formCampagne) if returns false, that means none of the checkbox is selected, else it will give you array of values.
$message = "Hi Rick,
Je hebt weer een offerte aanvraag ontvangen voor Limburg Media! :)
Name: $yourname
E-mail: $email
Telefoon: $telephone
Offerte aanvraag? $formCampagne
Comments: $comments
End of message
";
Instead of $formCampagne, you should try something like this:
$message = "Hi Rick,
Je hebt weer een offerte aanvraag ontvangen voor Limburg Media! :)
Name: $yourname
E-mail: $email
Telefoon: $telephone
Offerte aanvraag? ".implode(', ', $formCampagne)."
Comments: $comments
End of message
";
That should give a list of all the selected checkbox values separated by commas.