I am trying to make an contact form for my website and I am using the following code. I don't know why the selector keeps reseting when the text fields don't.
Anyone know a soultion for this? Or what I am doing wrong.
( It resets when the error check is done, and fails )
<?php
session_start();
$php_self = $_SERVER['PHP_SELF'];
// on submit
if( isset($_POST[name]) && isset($_POST[email]) && isset($_POST[message]) && isset($_POST[captcha]) ){
$name = $_POST[name];
$email = $_POST[email];
$telefon = $_POST[telefon];
$option = $_POST[option];
$message = $_POST[message];
$captcha = $_POST[captcha];
$error = 0;
// name
if( $name == "" ){ $error ++; $error_name = "class='error'"; }
// email
if( $email == "" ){ $error ++; $error_email = "class='error'"; }
// message
if( $message == "" ){ $error ++; $error_message = "class='error'"; }
// captcha
if( $captcha == "" || $captcha != $_SESSION[captcha]){ $error ++; $error_captcha = "class='error'"; }
// no error, send email
if( $error == 0){
// your email address
$address = "surrealcmstest#outlook.com";
// email subject
$subject = "x , Nytt Meddelande \r\n";
// email content
$content = "Namn: $name \r\nE-postadress: $email \r\nTelefon Nr: $telefon \r\nKontakta mig via: $option \r\nMeddelande: $message";
// html email
$email_content = "".$subject."";
$email_content .= "";
$email_content .= $content;
$email_content .= "";
// send email
mail($address, $subject, $email_content, "From: $email\r\nReply-To: $email\r\nReturn-Path: $email\r\n");
// reset variables
$name = ""; $email = ""; $message = "";
$mail_sent = 1;
}
}
// captcha
$num = rand(1, 20);
$num2 = rand(1, 9);
$verif = $num . " + " . $num2;
$_SESSION[captcha] = $num + $num2;
if( $mail_sent == 1 ){
echo "<div class=","sucess",">Ditt meddelande har skickats, vi återkommer så fort som möjligt.</div>";
} else {
echo "
<form action='".$php_self."' method='post'>
<p><span class='required'>* är obligatoriska fält.</span></p>
<p><strong>Namn:</strong> <span class='required'>*</span></p>
<input type='text' ".$error_name." name='name' value='".$name."'>
<p><strong>E-postadress:</strong> <span class='required'>*</span></p>
<input type='email' ".$error_email." name='email' value='".$email."'>
<p><strong>Telefon Nr:</strong></p>
<input type='telefon' name='telefon' value='".$telefon."'>
<p><strong>Kontakta mig via:</strong></p>
<select name='option'>
<option value='-'>-</option>
<option value='Telefon'>Telefon</option>
<option value='E-post'>E-post</option>
</select>
<p><strong>Meddelande:</strong> <span class='required'>*</span></p>
<textarea ".$error_message." name='message'>".$message."</textarea>
<p><strong>Hur mycket är ".$verif."?</strong> <span class='required'>*</span></p>
<input type='text' ".$error_captcha." name='captcha' value=''><br/>
<button>Skicka</button>
</form>";
}
?>
You have to add a check for each option Tag like you do with the inputs and load from the $_POST value before...
$option = $_POST['option'];
And in the select
<select name='option'>
<option value='-'>-</option>
<option value='Telefon' ".($option == 'Telefon' ? "selected":"").">Telefon</option>
<option value='E-post' ".($option == 'E-post'? "selected" : "").">E-post</option>
</select>
Edited:
Changed it to the inline string statement for the output string that the OP is generating...
Related
I am trying to display the name from the input field on a contact form to show the name that was entered after the email was submitted, I have changed headers in php and it has changed from cgi-mailer to unbknown sender? How do i get it to display the name of the person whosent the email from the contact form?
Thanks
form process php that controls validtion etc
// define variables and set to empty values
$name_error = $email_error = "";
$name = $email = $message = $success = "";
$from = $_POST['name1'];
//form is submitted with POST method
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name1"])) {
$name_error = "Name is required";
} else {
$name = test_input($_POST["name1"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$name_error = "Only letters and white space allowed";
}
}
if (empty($_POST["email"])) {
$email_error = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$email_error = "Invalid email format";
}
}
if (empty($_POST["message"])) {
$message = "";
} else {
$message = test_input($_POST["message"]);
}
if ($name_error == '' and $email_error == '' ){
$message_body = '';
unset($_POST['submit']);
foreach ($_POST as $key => $value){
$message_body .= "$key: $value\n";
}
$to = 'devonfoodmovement#gmail.com';
$subject = 'Contact Form Submit';
$headers = "From:" . $from;
if (mail($to, $subject, $message, $headers)){
$success = "Message sent";
$name = $email = $message = '';
}
}
/*if(isset($_POST['submit'])) {
$from = $_POST['name1'];
$headers = "From:" . $from;
}*/
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
Conotact form html
<?php include('form_process.php');
/*if (isset($_POST['contact-submit'])){
$url = 'https://www.google.com/recaptcha/api/siteverify';
$privatekey = "secretkeygoogle";
$response = file_get_contents($url."?secret=".$privatekey."&response=".$_POST['g-recaptcha-response']."&remoteip=".$_SERVER['REMOTE_ADOR']);
$data = json_decode($response);
if(isset($data->success) AND $data->success==true) {
}else{
}
}*/
?>
<div class="home-btn"><i class="fas fa-home"></i></div>
<div class='grey'>
<div class="container-contact">
<form id="contact" method="post">
<div id="column-contact-left">
<div class='contact-logo'></div>
<h3>Contact the Devon Food Movement</h3>
<fieldset>
<input placeholder="Your name" type="text" tabindex="1" name="name1" value="<?= $name ?>" autofocus>
</fieldset>
<span class="error"><?= $name_error ?></span>
<fieldset>
<input placeholder="Your Email Address" type="text" name="email" value="<?= $email ?>" tabindex="2" >
</fieldset>
<span class="error"><?= $email_error ?></span>
</div>
<div id="column-contact-right">
<fieldset>
<textarea placeholder="Type your Message Here...." name="message" value="<?= $message ?>" tabindex="3" ></textarea>
</fieldset>
<div class="g-recaptcha" data-sitekey="needtoinput" ></div>
<span class="success"><?= $success; ?></span>
<fieldset>
<button name="submit" type="submit" id="contact-submit" data-submit="...Sending">Submit</button>
</fieldset>
</div>
</form>
</div>
</div>
New form p[rocess php with seperate mail function
<?php
// define variables and set to empty values
$name_error = $email_error = "";
$name = $email = $message = $success = "";
//form is submitted with POST method
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name1"])) {
$name_error = "Name is required";
} else {
$name = test_input($_POST["name1"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$name_error = "Only letters and white space allowed";
}
}
if (empty($_POST["email"])) {
$email_error = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$email_error = "Invalid email format";
}
}
if (empty($_POST["message"])) {
$message = "";
} else {
$message = test_input($_POST["message"]);
}
if ($name_error == '' and $email_error == '' ){
$message_body = '';
unset($_POST['submit']);
foreach ($_POST as $key => $value){
$message_body .= "$key: $value\n";
}
$to = 'devonfoodmovement#gmail.com';
$subject = 'Contact Form Submit';
if (mail($to, $subject, $message, $headers)){
$success = "Message sent";
$name = $email = $message = '';
}
}
/*if(isset($_POST['submit'])) {
$from = $_POST['name1'];
$headers = "From:" . $from;
}*/
}
$from = $_POST['name1'];
$headers = "From:" . $from;
if (isset($_POST['submit'])) {
mail($headers);
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
LATEST PHP for the last comment i made
if ($name_error == '' and $email_error == '' ){
$message_body = '';
unset($_POST['submit']);
foreach ($_POST as $key => $value){
$message_body .= "$key: $value\n";
}
$email = $_POST['email'];
$to = 'devonfoodmovement#gmail.com';
$subject = 'Contact Form Submit';
$headers = 'From:' . $email . "\n" . 'Reply-to: ' . $email . "\n" ;
if (mail($to, $subject, $message, $headers)){
$success = "Message sent";
$name = $email = $message = '';
}
}
You must have the required fields on your form, then if you want, ask for the name too.
<?php
function defaultMailing($to, $subject, $txt, $headers){
if(mail($to, $subject, $txt, $headers)) return true; else return false;
}
?>
on the other part (where your form action):
$to = $_POST['to'];
$subject = $_POST['subject'];
$txt = $_POST['message'];
//you don't need name, but if you asked for on the form:
$msg = "thanks, ".$_POST['name']." for your message, your request will be answered soon.";
//call to mail function and send the required (to, subject and text/html message) and the optional headers if you want
defaultMailing($to, $subject, $txt, $headers);
//do whatever you want with $msg or with $_POST['name'];
If you want to insert the posted name on the message, simply modify $txt var setting the $_POST['name'] wherever you want and then, proceed with defaultMailing call, for example:
$to = $_POST['to'];
$subject = $_POST['subject'];
$txt = $_POST['message'];
$name = $_POST['name'];
$mailMessage = $name.' '.$txt;
//call to mail function and send the required (to, subject and text/html message) and the optional headers if you want
defaultMailing($to, $subject, $mailMessage, $headers);
Settles for the email being the from sender as it appears that a from value has to be a valid email address
if ($name_error == '' and $email_error == '' and ($res['success']) ){
$message_body = '';
unset($_POST['submit']);
foreach ($_POST as $key => $value){
$message_body .= "$key: $value\n";
}
$email = $_POST['email'];
$to = 'devonfoodmovement#gmail.com';
$subject = 'Contact Form Submit';
$headers = 'From:' . $email . "\n" . 'Reply-to: ' . $email . "\n" ;
if (mail($to, $subject, $message, $headers)) {
$sent = "Message sent";
$name = $email = $message = '';
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 8 years ago.
Improve this question
I have added Quick enquiry form to woocommerce product page. but it contains only Name,Email, subject & enquiry option.
Take a look here http://demo.hashkart.com
I want to add exta field called phone no. in this form
Please suggest me solution for this or any extra plugins.
NOTE : Take back up before implementing this.
Go to wp-content > plugins > product-enquiry-for-woocommerce > data >contact.php
And replace content of contact.php with following code :
<?php
/* SimpleModal Contact Form
* http://simplemodal.com/
* http://code.google.com/p/simplemodal/
*
* Copyright (c) 2012 Eric Martin - http://ericmmartin.com
*
* Licensed under the MIT license:
* http://www.opensource.org/licenses/mit-license.php
*
* Revision: $Id: contact-dist.php 269 2011-12-17 23:24:14Z emartin24 $
*
*/
//date_default_timezone_set('America/Los_Angeles');
global $to;
if(isset($_POST['wdm_form_dataset']))
{
$form_data = $_POST['wdm_form_dataset'];
}
if(isset($_POST['wdm_admin_email']))
{
$to_adm = $_POST['wdm_admin_email'];
}
if(isset($_POST['wdm_site_name']))
{
$site_name = $_POST['wdm_site_name'];
}
// User settings
if (!empty($form_data['user_email']))
$to = $form_data['user_email'];
else if(isset($to_adm))
$to = $to_adm;
if (!empty($form_data['default_sub']))
$subject = $form_data['default_sub'];
else if(isset($site_name))
$subject = "Enquiry for a product from ".$site_name;
//Include extra form fields and/or submitter data?
//false = do not include
$extra = array(
"form_subject" => true,
"your_number" =>true,
"form_cc" => (isset($form_data['enable_send_mail_copy']) ? true : false),
"ip" => false,
"user_agent" => false
);
// Process
$action = isset($_POST["action"]) ? $_POST["action"] : "";
if (empty($action)) {
// Send back the contact form HTML
$output = "<div style='display:none'>
<div class='contact-top'></div>
<div class='contact-content'>
<h1 class='contact-title'>Product Enquiry:</h1>
<div class='contact-loading' style='display:none'></div>
<div class='contact-message' style='display:none'></div>
<form action='#' style='display:none'>
<input type='text' id='wdm_product_name' class='contact-input' name='wdm_product_name' value='' readonly=true />
<label for='contact-name'>*Name:</label>
<input type='text' id='contact-name' class='contact-input' name='name' tabindex='1001' />
<label for='contact-email'>*Email:</label>
<input type='text' id='contact-email' class='contact-input' name='email' tabindex='1002' />";
if ($extra["form_subject"] && $extra["your_number"]) {
$output .= "
<label for='contact-subject'>Subject:</label>
<input type='text' id='contact-subject' class='contact-input' name='subject' value='' tabindex='1003' />";
$output .= "
<label for='contact-phone'>Phone Number:</label>
<input type='text' id='contact-phone' class='contact-input' name='phone' value='' tabindex='1007' />";
}
$output .= "<input type='hidden' id='wdm_product_url' class='contact-input' name='wdm_product_url' value='' />";
$output .= "<input type='hidden' id='wdm_form_mail_to' class='contact-input' name='wdm_form_mail_to' value='' />";
$output .= "<input type='hidden' id='wdm_form_def_sub' class='contact-input' name='wdm_form_def_sub' value='' />";
$output .= "<input type='hidden' id='wdm_website_name' class='contact-input' name='wdm_website_name' value='' />";
$output .= "
<label for='contact-message'>*Enquiry:</label>
<textarea id='contact-message' class='contact-input' name='message' cols='40' rows='4' tabindex='1004'></textarea>
<br/>";
if ($extra["form_cc"]) {
$output .= "
<label> </label>
<input type='checkbox' id='contact-cc' name='cc' value='1' tabindex='1005' /> <span class='contact-cc'>Send me a copy</span>
<br/>";
}
$output .= "
<label> </label>
<button type='submit' class='contact-send contact-button' tabindex='1006'>Send</button>
<button type='submit' class='contact-cancel contact-button simplemodal-close' tabindex='1007'>Cancel</button>
<br/>
<input type='hidden' name='token' value='" . smcf_token($to) . "'/>
</form>
</div>
<div class='contact-bottom'><a href='http://wisdmlabs.com' target='_blank'>Powered by WisdmLabs</a></div>
</div>";
echo $output;
$to = base64_encode($to);
$subject = base64_encode($subject);
$site_name = base64_encode($site_name);
echo '<script type="text/javascript">
jQuery(document).ready(
function()
{
jQuery("#wdm_form_mail_to").val("'.$to.'");
jQuery("#wdm_form_def_sub").val("'.$subject.'");
jQuery("#wdm_website_name").val("'.$site_name.'");
}
);
</script>';
}
else if ($action == "wdm_send") {
// Send the email
//echo "<pre>";print_r($_REQUEST);echo "</pre>";exit;
$name = isset($_POST["name"]) ? $_POST["name"] : "";
$email = isset($_POST["email"]) ? $_POST["email"] : "";
$urphone = isset($_POST["phone"]) ? $_POST["phone"] : "";
$subject = isset($_POST["wdm_form_def_sub"]) ? $_POST["wdm_form_def_sub"] : "";
$subject = base64_decode($subject);
$subject = !empty($_POST["subject"]) ? $_POST["subject"] : $subject;
$product_url = isset($_POST["wdm_product_url"]) ? $_POST["wdm_product_url"] : "";
$product_name = isset($_POST["wdm_product_name"]) ? $_POST["wdm_product_name"] : "";
$message = isset($_POST["message"]) ? $_POST["message"] : "";
$cc = isset($_POST["cc"]) ? $_POST["cc"] : "";
$token = isset($_POST["token"]) ? $_POST["token"] : "";
$to = isset($_POST["wdm_form_mail_to"]) ? $_POST["wdm_form_mail_to"] : "";
$to = base64_decode($to);
//echo $to;exit;
$site_name = isset($_POST["wdm_website_name"]) ? $_POST["wdm_website_name"] : "";
$site_name = base64_decode($site_name);
// make sure the token matches
if ($token === smcf_token($to)) {
smcf_send($name, $email, $subject, $urphone, $product_url, $product_name, $site_name, $message, $cc);
echo "Your enquiry sent successfully. We will get back to you soon.";
}
else {
echo "Unfortunately, your enquiry could not be verified.";
}
}
function smcf_token($s) {
return md5("smcf-" . $s . date("WY"));
}
// Validate and send email
function smcf_send($name, $email, $subject, $urphone, $product_url, $product_name, $site_name, $message, $cc) {
global $to, $extra;
// Filter and validate fields
$name = smcf_filter($name);
$subject = smcf_filter($subject);
$email = smcf_filter($email);
if (!smcf_validate_email($email)) {
$subject .= " - invalid email";
$message .= "\n\nBad email: $email";
$email = $to;
$cc = 0; // do not CC "sender"
}
// Add additional info to the message
if ($extra["ip"]) {
$message .= "\n\nIP: " . $_SERVER["REMOTE_ADDR"];
}
if ($extra["user_agent"]) {
$message .= "\n\nUSER AGENT: " . $_SERVER["HTTP_USER_AGENT"];
}
// Set and wordwrap message body
$body = "Product Enquiry from <strong>". $site_name . "</strong> <br /><br />";
$body .= "<strong>Product Name:</strong> '". $product_name ."'<br /><br />";
$body .= "<strong>Product URL:</strong> ". $product_url ."<br /><br />";
$body .= "<strong>Customer Name:</strong> ". $name ."<br /><br />";
$body .= "<strong>Customer Email:</strong> ". $email ."<br /><br />";
$body .= "<strong>Customer Phone Number:</strong> ". $urphone ."<br /><br />";
$body .= "<strong>Message:</strong> <br />". $message;
$body = wordwrap($body, 100);
// Build header
$headers = "From: $email\n";
$headers .= "Reply-To: $email \n";
if ($cc == 1) {
$headers .= "Cc: $email\n";
}
// $headers .= "X-Mailer: PHP/SimpleModalContactForm";
// UTF-8
if (function_exists('mb_encode_mimeheader')) {
$subject = mb_encode_mimeheader($subject, "UTF-8", "B", "\n");
}
else {
// you need to enable mb_encode_mimeheader or risk
// getting emails that are not UTF-8 encoded
}
$headers .= "MIME-Version: 1.0\n";
$headers .= "Content-type: text/html; charset=utf-8\n";
$headers .= "Content-Transfer-Encoding: quoted-printable\n";
//echo "to ".$to."<br>";
//echo "subject ".$subject."<br>";
//echo "body ".$body."<br>";
//echo "headers ".$headers."<br>";exit;
wp_mail($to, $subject, $body, $headers) or die("Unfortunately, a server issue prevented delivery of your message.");
//wp_mail($to, $subject, $body, $headers) or
// die("Unfortunately, a server issue prevented delivery of your message.");
}
// Remove any un-safe values to prevent email injection
function smcf_filter($value) {
$pattern = array("/\n/","/\r/","/content-type:/i","/to:/i", "/from:/i", "/cc:/i");
$value = preg_replace($pattern, "", $value);
return $value;
}
// Validate email address format in case client-side validation "fails"
function smcf_validate_email($email) {
$at = strrpos($email, "#");
// Make sure the at (#) sybmol exists and
// it is not the first or last character
if ($at && ($at < 1 || ($at + 1) == strlen($email)))
return false;
// Make sure there aren't multiple periods together
if (preg_match("/(\.{2,})/", $email))
return false;
// Break up the local and domain portions
$local = substr($email, 0, $at);
$domain = substr($email, $at + 1);
// Check lengths
$locLen = strlen($local);
$domLen = strlen($domain);
if ($locLen < 1 || $locLen > 64 || $domLen < 4 || $domLen > 255)
return false;
// Make sure local and domain don't start with or end with a period
if (preg_match("/(^\.|\.$)/", $local) || preg_match("/(^\.|\.$)/", $domain))
return false;
// Check for quoted-string addresses
// Since almost anything is allowed in a quoted-string address,
// we're just going to let them go through
if (!preg_match('/^"(.+)"$/', $local)) {
// It's a dot-string address...check for valid characters
if (!preg_match('/^[-a-zA-Z0-9!#$%*\/?|^{}`~&\'+=_\.]*$/', $local))
return false;
}
// Make sure domain contains only valid characters and at least one period
if (!preg_match("/^[-a-zA-Z0-9\.]*$/", $domain) || !strpos($domain, "."))
return false;
return true;
}
//exit;
?>
Reminder: Plugin providing that feature in PRO version.So please use that.I am posting it just for temporary usage and I have not seen its License of usage.
Please let me know either its working or not because its UNTESTED.
I have website (dastiche.kz) and there is newsletter subscription. I have modified a bit my subscription, adding some "iframe", so that echo would appear without redirecting to another page. Everything now works well, but I now got annoying problem. Everytime I go to my main page(where the subscription form is located) or just refresh it, php is triggered and I receive blank email as though someone has made subscription. What did I do wrong?
<iframe name="myiframe" src="myiframe.php" width="100%" height="60px" frameborder="0"></iframe>
<form method="POST" action="myiframe.php" class="subscribe" target="myiframe">
<p><input type="text" name="Name" maxlength="10" style="font-family:'Times New Roman', Times, serif" value="Ваше имя" onfocus="if (this.value == 'Ваше имя') {this.value = '';}" onblur="if (this.value == '') {this.value ='Ваше имя';}" class="line"></p>
<p><input type="email" name="Email" maxlength="40" style="font-family:'Times New Roman', Times, serif" value="Ваш email" onfocus="if (this.value == 'Ваш email') {this.value = '';}" onblur="if (this.value == '') {this.value ='Ваш email';}" class="line"></p>
<p><input type="image" value="submit" name="Submit" src="img/subscribe.png" class="imgsub"></p>
</form>
<?php
Header("Content-Type: text/html; charset=utf-8");
$recipient = "order#dastiche.kz";
$subject = "Subscriber";
$name = $_POST['Name'];
$email = $_POST['Email'];
$location = "index.html";
$sender = $recipient;
$body .= "Name: ".$_REQUEST['Name']." \n";
$body .= "Email: ".$_REQUEST['Email']." \n";
if (($name != "") and ($email != ""))
// Если существуют проверяем...
{
if ((strlen($name) >= 2) and (strlen($name) <= 25))
{
$name = stripslashes($name);
$name = html_entity_decode($name);
$name = strip_tags($name);
}
else
{
echo " something is wrong with name field ";
echo "<center><input name='back' type='button' value='get back'
onclick= 'javascript:history.back()'></center>";
}
if (eregi("^[._a-zA-Z0-9-]+#[.a-zA-Z0-9-]+.[a-z]{2,6}$", $email))
{
$email = stripslashes($email);
$email = htmlspecialchars($email);
$email = strip_tags($email);
}
else
{
echo "There are some mistakes in the \"E-mail\" field";
echo "<center><input name='back' type='button' value='try again'
onclick= 'javascript:history.back()'></center>";
}
}
// Если не существуют выводим сообщение...
else
{
echo "Заполните следующие поля:";
}
if (($name) and ($email))
{
echo "Спасибо за подписку!";
}
mail( $recipient, $subject, $body, "From: $sender" ) or die ("Mail could not be sent.");
?>
As i Commented put a condition above of your code
if(isset($_POST['Submit']))
{
// here put your complete php code
}
This will check if the POST request in received with the name of Submit. so the code will execute when you press the submit button Like
<?php
if(isset($_POST['Submit']))
{
Header("Content-Type: text/html; charset=utf-8");
$recipient = "order#dastiche.kz";
$subject = "Subscriber";
$name = $_POST['Name'];
$email = $_POST['Email'];
$location = "index.html";
$sender = $recipient;
$body .= "Name: ".$_REQUEST['Name']." \n";
$body .= "Email: ".$_REQUEST['Email']." \n";
if (($name != "") and ($email != ""))
// ???? ?????????? ?????????...
{
if ((strlen($name) >= 2) and (strlen($name) <= 25))
{
$name = stripslashes($name);
$name = html_entity_decode($name);
$name = strip_tags($name);
}
else
{
echo " something is wrong with name field ";
echo "<center><input name='back' type='button' value='get back'
onclick= 'javascript:history.back()'></center>";
}
if (eregi("^[._a-zA-Z0-9-]+#[.a-zA-Z0-9-]+.[a-z]{2,6}$", $email))
{
$email = stripslashes($email);
$email = htmlspecialchars($email);
$email = strip_tags($email);
}
else
{
echo "There are some mistakes in the \"E-mail\" field";
echo "<center><input name='back' type='button' value='try again'
onclick= 'javascript:history.back()'></center>";
}
}
// ???? ?? ?????????? ??????? ?????????...
else
{
echo "????????? ????????? ????:";
}
if (($name) and ($email))
{
echo "??????? ?? ????????!";
}
mail( $recipient, $subject, $body, "From: $sender" ) or die ("Mail could not be Sent");
}
?>
Can someone tell me why this is not displaying the form? If I go to the address that I have it hosted on, the page just displays "Your message has been sent. Thank you, ." It seems to just execute and display the last function.
<?php
function validateInput($data, $fieldName) {
global $errorCount;
if (empty($data)) {
echo "\"$fieldName\" is a required field.<br />\n";
++$errorCount;
$retval = "";
} else { // only clean up the input if it isn't empty
$retval = trim($data);
$retval = stripsplashes($retval);
}
return($retval);
}
function validateEmail($data, $fieldName) {
global $errorCount;
if (empty($data)) {
echo "\"$fieldName\" is a required field.<br />\n";
++$errorCount;
$retval = "";
} else { // only clean up the input if it isn't empty
$retval = trim($data);
$retval = stripsplashes($retval);
$pattern = "/^[\w-]+(\.[\w-]+)*#" . "[\w-]+(\.[\w-]+)*" . "(\.[[a-z]]{2,})$/i";
if (preg_match($pattern, $retval) == 0) {
echo "\"$fieldName\" is not a valid e-mail address.<br />\n";
++$errorCount;
}
}
return($retval);
}
function displayForm($Sender, $Email, $Subject, $Message) {
?>
<h2 style = "text-align:center">Contact Me</h2>
<form name="contact" action="ContactForm.php" method="post">
<p>Your name: <input type="text" name="Sender" value="<?php echo $Sender; ?>" /></p>
<p>Your E-mail: <input type="text" name="Email" value="<?php echo $Sender; ?>" /></p>
<p>Subject: <input type="text" name="Subject" value="<?php echo $Subject; ?>" /></p>
<p>Message:<br />
<textarea name="Message"><?php echo $Message; ?></textarea></p>
<p><input type="reset" value="Clear Form" /> <input type="submit" name="Submit" value="Send Form" /></p>
</form>
<?php
}
$ShowForm = TRUE;
$errorCount = 0;
$Sender = "";
$Email = "";
$Subject = "";
$Message = "";
if (isset($_POST['Submit'])) {
$Sender = validateInput($_POST['Sender'],"Your Name");
$Email = validateInput($_POST['Email'],"Your E-mail");
$Subject = validateInput($_POST['Subject'],"Subject");
$Message = validateInput($_POST['Message'],"Message");
if ($errorCount == 0)
$ShowForm = FALSE;
else
$ShowForm = TRUE;
}
if ($ShowForm == TRUE)
if ($errorCount>0) {// if there were errors
echo "<p>Please re-enter the form information below.</p>\n";
displayForm($Sender, $Email, $Subject, $Message);
} else {
$SenderAddress = "$Sender <$Email>";
$Headers = "From: $SenderAddress\nCC: $SenderAddress\n";
// Substitute your own e-mail address for recipient#example.com
$result = mail("recipient#example.com", $Subject, $Message, $Headers);
if ($result)
echo "<p>Your message has been sent. Thank you, " . $Sender . ".</p>\n";
else
echo "<p>There was an error sending your message, " . $Sender . ".</p>\n";
}
?>
You have:
$showForm = TRUE;
Which, when the form has not yet been submitted, will lead to the conditional statement always being true with $errorCount == 0. You don't call displayForm() in the else case of that conditional.
Hope this helps.
Ok, the error was because curly brace should've been after the if ($ShowForm == TRUE) instead of the if ($errorCount>0).
So I have a form with both javascript validation to check each field is filed and a jquery ajax script to stop the page reloading.
The PHP script is very simple and only emails the fields of the form.
The problem is I need to ONLY show the thank you message if each field is filled out, and at the moment it appears to be showing it when I just enter the name field.
It doesn't show it if i just enter either the email or message field though and I can't work out why (I'm bad at PHP).
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$priority = $_POST['priority'];
$message = $_POST['message'];
$telephone = $_POST['telephone'];
$formcontent="From: $name \n Email: $email \n Telephone Number: $telephone \n Priority: $priority \n Message: $message";
$recipient = "myemail#address.co.uk";
$subject = "Contact Form";
$mailheader = "From: $email \r\n";
mail($recipient, $subject, $formcontent, $mailheader) or die("Error!");
if(mail($name,$email,$message,$headers)){
echo "<p>Thanks for your mail...</p>";
}
?>
Javascript that stops page reloading.
<script type="text/javascript">
$(document).ready(function() {
$(".contactus").submit(function() {
$.post("mail.php", $(".contactus").serialize(),
function(data) {
$("#formResponse").html(data);
}
);
return false;
});
});
</script>
Form validation.
<script type="text/javascript" language="JavaScript">
var FormName = "contactus";
var RequiredFields = "name,email,priority,message";
function ValidateRequiredFields()
{
var FieldList = RequiredFields.split(",")
var BadList = new Array();
for(var i = 0; i < FieldList.length; i++) {
var s = eval('document.' + FormName + '.' + FieldList[i] + '.value');
s = StripSpacesFromEnds(s);
if(s.length < 1) { BadList.push(FieldList[i]); }
}
if(BadList.length < 1) { return true; }
var ess = new String();
if(BadList.length > 1) { ess = 's'; }
var message = new String('\n\nThe following field' + ess + ' are required:\n');
for(var i = 0; i < BadList.length; i++) { message += '\n' + BadList[i]; }
alert(message);
return false;
}
function StripSpacesFromEnds(s)
{
while((s.indexOf(' ',0) == 0) && (s.length> 1)) {
s = s.substring(1,s.length);
}
while((s.lastIndexOf(' ') == (s.length - 1)) && (s.length> 1)) {
s = s.substring(0,(s.length - 1));
}
if((s.indexOf(' ',0) == 0) && (s.length == 1)) { s = ''; }
return s;
}
// -->
</script>
And the form
<form action="mail.php" id="myform" class="contactus" onsubmit="return ValidateRequiredFields(); this.submit(); this.reset(); return false;" name="contactus" method="POST">
<p class="floatleft" style="width:200px; background-color:#FF0000; height:50px; line-height:50px; margin:0; padding:0;">Nameeeeee</p> <input class="sizetext" type="text" maxlength="10" name="name">
<div style="clear:both"></div>
<p class="floatleft" style="width:200px;">Email</p> <input class="sizetext" type="text" maxlength="10" name="email">
<div style="clear:both"></div>
<p class="floatleft" style="width:200px;">Telephone</p> <input class="sizetext" type="text" maxlength="10" name="telephone">
<p>Priority</p>
<select name="priority" size="1">
<option value="Low">Low</option>
<option value="Normal">Normal</option>
<option value="High">High</option>
<option value="Emergency">Emergency</option>
</select>
</select>
<p>Message</p><textarea name="message" rows="6" cols="25"></textarea><br />
<br />
<input class="buttonstyle" type="submit" value="Send">
</form>
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$priority = $_POST['priority'];
$message = $_POST['message'];
$telephone = $_POST['telephone'];
$check = array('name', 'email', 'priority', 'message', 'telephone');
$send = true;
foreach($check as $key => $value){
if(empty($_POST[$value])){
$send = false;
}
}
$formcontent="From: $name \n Email: $email \n Telephone Number: $telephone \n Priority: $priority \n Message: $message";
$recipient = "myemail#address.co.uk";
$subject = "Contact Form";
$mailheader = "From: $email \r\n";
if($send && mail($recipient, $subject, $formcontent, $mailheader)){
echo "<p>Thanks for your mail...</p>";
}
else{
die('Error!');
}
Well, the most easier way would be to check if your POST fields are present and not empty. Probably there is a more elegant solution if you want to check every field individually, but here goes:
if (isset($_POST['name']) && !empty($_POST['name']) && isset($_POST['email']) && !empty($_POST['email']) && isset($_POST['message']) && !empty($_POST['message'])) {
if(mail($name,$email,$message,$headers)){
echo "<p>Thanks for your mail...</p>";
}
}
You need to wrap your code around
if(isset($_POST['submit']))
{
$name = $_POST['name'];
$email = $_POST['email'];
$priority = $_POST['priority'];
$message = $_POST['message'];
$telephone = $_POST['telephone'];
$formcontent="From: $name \n Email: $email \n Telephone Number: $telephone \n Priority: $priority \n Message: $message";
$recipient = "myemail#address.co.uk";
$subject = "Contact Form";
$mailheader = "From: $email \r\n";
$mail = #mail($recipient, $subject, $formcontent, $mailheader);
if($mail){
echo "<p>Thanks for your mail...</p>";
}
else
{
echo "Error Sending Mail " ;
}
}