I'm relatively new to WordPress and PHP, however I am trying to create my own shortcode plugin, which I have completed and is working.
However if I add more than 1 on the same page in WP, both forms submit and are not exclusive of each other.
I have search around the web, but can't find out how to easily separate the form id's, below is my plugin code:
function wptuts_contact_form_sc($atts, $content = null) {
extract(shortcode_atts(array(
//"email" => get_bloginfo('admin_email'),
"id" => '',
"attachment" => '',
"desc" => '',
"subject" => '',
"label_email" => 'Your E-mail Address',
"label_submit" => 'Submit',
"error_empty" => 'Please fill in all the required fields.',
"error_noemail" => 'Please enter a valid e-mail address.',
"success" => 'Thanks, your voucher has been sent to '
), $atts));
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$error = false;
$required_fields = array("email");
foreach ($_POST as $field => $value) {
if (get_magic_quotes_gpc()) {
$value = stripslashes($value);
}
$form_data[$field] = strip_tags($value);
}
foreach ($required_fields as $required_field) {
$value = trim($form_data[$required_field]);
if(empty($value)) {
$error = true;
$result = $error_empty;
}
}
if(!is_email($form_data['email'])) {
$error = true;
$result = $error_noemail;
}
if ($error == false) {
$email_subject = "Eurest Voucher - " . $desc;
$email_message = "Hi, Your requested voucher/offer is attached to this email.";
$headers = "From: Eurest Vouchers <Vouchers#eurestfood.com>\n";
$headers .= "Content-Type: text/plain; charset=UTF-8\n";
$headers .= "Content-Transfer-Encoding: 8bit\n";
$attachments = array(WP_CONTENT_DIR . $attachment);
$email = $form_data['email'];
wp_mail($email, $email_subject, $email_message, $headers, $attachments);
$result = $success . $form_data['email'];
$sent = true;
}
}
if($result != "") {
$info = '<div class="info">'.$result.'</div>';
}
$email_form = '<form class="contact-form" method="post" id="'.$id.'" action="'.get_permalink().'">
<div>
<label for="cf_email">'.$label_email.':</label>
<input type="text" name="email" id="cf_email" size="50" maxlength="50" value="'.$form_data['email'].'" /><input type="submit" value="'.$label_submit.'" name="send" id="cf_send" />
</div>
</form>';
if($sent == true) {
return $info;
} else {
return $info.$email_form;
}
} add_shortcode('emailattachment', 'wptuts_contact_form_sc');
If someone can help that would be appreciated.
Thanks,
Steve
I am pretty sure you've forgotten the last attribute in the function shortcode_atts, even if it's optionnal, you need to call it.
Also, is there some code missing ?
edit : you need to id your forms otherwise the function will pick up the datas twice. call the second shortcode giving the value 'second' to teh variable $num_f like so [wptuts_contact_form_sc -your bunch of vars here- num_f="second"]
function wptuts_contact_form_sc($atts, $content = null) {
extract(shortcode_atts(array(
//"email" => get_bloginfo('admin_email'),
"id" => '',
"attachment" => '',
"desc" => '',
"subject" => '',
"label_email" => 'Your E-mail Address',
"label_submit" => 'Submit',
"error_empty" => 'Please fill in all the required fields.',
"error_noemail" => 'Please enter a valid e-mail address.',
"success" => 'Thanks, your voucher has been sent to ',
"num_f" => 'first'
), $atts));
if ($_SERVER['REQUEST_METHOD'] == 'POST' && $num_f == 'second') {
$error = false;
$required_fields = array("email");
foreach ($_POST as $field => $value) {
if (get_magic_quotes_gpc()) {
$value = stripslashes($value);
}
$form_data[$field] = strip_tags($value);
}
foreach ($required_fields as $required_field) {
$value = trim($form_data[$required_field]);
if(empty($value)) {
$error = true;
$result = $error_empty;
}
}
if(!is_email($form_data['email'])) {
$error = true;
$result = $error_noemail;
}
if ($error == false) {
$email_subject = "Eurest Voucher - " . $desc;
$email_message = "Hi, Your requested voucher/offer is attached to this email.";
$headers = "From: Eurest Vouchers <Vouchers#eurestfood.com>\n";
$headers .= "Content-Type: text/plain; charset=UTF-8\n";
$headers .= "Content-Transfer-Encoding: 8bit\n";
$attachments = array(WP_CONTENT_DIR . $attachment);
$email = $form_data['email'];
wp_mail($email, $email_subject, $email_message, $headers, $attachments);
$result = $success . $form_data['email'];
$sent = true;
}
}
if($result != "") {
$info = '<div class="info">'.$result.'</div>';
}
$email_form = '<form class="contact-form" method="post" id="'.$id.'" action="'.get_permalink().'">
<div>
<label for="cf_email">'.$label_email.':</label>
<input type="text" name="email" id="cf_email" size="50" maxlength="50" value="'.$form_data['email'].'" /><input type="submit" value="'.$label_submit.'" name="send" id="cf_send" />
</div>
</form>';
if($sent == true) {
return $info;
} else {
return $info.$email_form;
}
} add_shortcode('emailattachment', 'wptuts_contact_form_sc');
To have more than two forms, you can either do it manually by calling the third block 'trird' and so on, but that's not very good practice to be honest...
If I were you I would change your code at the core, create a function that would return the form with a hidden field like so : <input type"hidden" name="hidden" value=" . $nf . "> and then instead of controling $_SERVER['REQUEST_METHOD'], you'd control the value of $_POST['n'] after checking if it's set ofc.
Here's the code I came up with :
<?php
function wptuts_contact_form_sc($atts, $content = null) {
extract(shortcode_atts(array(
//"email" => get_bloginfo('admin_email'),
"id" => '',
"attachment" => '',
"desc" => '',
"subject" => '',
"label_email" => 'Your E-mail Address',
"label_submit" => 'Submit',
"error_empty" => 'Please fill in all the required fields.',
"error_noemail" => 'Please enter a valid e-mail address.',
"success" => 'Thanks, your voucher has been sent to ',
"nf" => '1'
), $atts));
if (isset($_POST['hidden'])) {
$hidden = $_POST['hidden'];
$error = false;
$required_fields = array("email");
foreach ($_POST as $field => $value) {
if (get_magic_quotes_gpc()) {
$value = stripslashes($value);
}
$form_data[$field] = strip_tags($value);
}
foreach ($required_fields as $required_field) {
$value = trim($form_data[$required_field]);
if(empty($value)) {
$error = true;
$result = $error_empty;
}
}
if(!is_email($form_data['email'])) {
$error = true;
$result = $error_noemail;
}
if ($error == false) {
$email_subject = "Eurest Voucher - " . $desc;
$email_message = "Hi, Your requested voucher/offer is attached to this email.";
$headers = "From: Eurest Vouchers <Vouchers#eurestfood.com>\n";
$headers .= "Content-Type: text/plain; charset=UTF-8\n";
$headers .= "Content-Transfer-Encoding: 8bit\n";
$attachments = array(WP_CONTENT_DIR . $attachment);
$email = $form_data['email'];
wp_mail($email, $email_subject, $email_message, $headers, $attachments);
$result = $success . $form_data['email'];
$sent = true;
}
} else {
$hidden = $_POST['hidden'];
}
for ($i = 1; $i <= $nf; $i++) {
if($result != "" && $i == $hidden) {
$info = '<div class="info">'.$result.'</div>';
}
$email_form = '<form class="contact-form" method="post" id="'.$id.'" action="'.get_permalink().'">
<div>
<label for="cf_email">'.$label_email.':</label>
<input type="hidden" name="hidden" value="' . $nf . '">
<input type="text" name="email" id="cf_email" size="50" maxlength="50" value="'.$form_data['email'].'" /><input type="submit" value="'.$label_submit.'" name="send" id="cf_send" />
</div>
</form>';
if($sent == true) {
return $info;
} else {
return $info . $email_form;
}
}
} add_shortcode('emailattachment', 'wptuts_contact_form_sc');
?>
Let me know if it works, (or does not) I obviously couldnt test it so there might be somehting wrong, in which case I just hope you got the whole idea behind it.
Related
So I am making a contact form where when we click submit, it should send an email to the admin including the inputs. the email function is already working, and what I am missing is validation to check whether input field is empty or not. I tried adding the required attribute in the input tag. and it works on localhost but not on the server for some reason. Also, it needs to pop up a message acknowledging that you have submitted the form. I used the onclick function here. but i cannot clarify whether it works, since it needs to only pop up the message when the submit is successful and there is no empty field.
Here is the code i used. connection was already established.
<!---Mail Starts-->
<?php
if (isset($_POST['submit'])) {
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
$headers .= 'From: Client<' . $_POST['mail'] . '>' . "\r\n";
$headers .= 'Reply-To: ' . $_POST['mail'] . "\r\n";
$headers .= 'X-Mailer: PHP/' . phpversion() . "\r\n";
$to = 'email#gmail.com';
$subject = "Send Us A Smile - ".$_POST['name'];
$message = "
<html>
<body>
<div style='font-family:arial;width:100%;padding:5px;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;box-sizing:border-box;'>
<div style='margin:0 auto;max-width:500px;padding:5px;text-align:center;background: -webkit-gradient(linear, 0% 0%, 0% 100%, from(#741C57), to(#360d29));background: -moz-linear-gradient(90deg, #360d29, #741C57);color:#fff;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;box-sizing:border-box;border-radius:15px;'>
</div>
<div style='text-align:center;padding:5px;color:#666;background-color:rgba(255,255,240,1);max-width:460px;margin:0 auto; border:2px solid #000;border-radius:0 0 5px 5px;'>
<h2 style='font-weight:200;line-height:.3em;'>
Send Us A Smile <br>
</h2>
<p style='text-align:left;'>
Name : " . $_POST['name'] . "<br>
Email : " . $_POST['mail'] . "<br>
Subject : " . $_POST['subject'] . "<br>
Message : " . $_POST['message'] . "
</p>
</div>
</div>
</body>
</html>
";
mail($to,$subject,$message,$headers);
}
?>
<!---Mail Ends-->
<div class="full" id="contactForm">
<div>
<form name ="contact" action="" method="POST">
<input type="hidden" name="recipient" value="info#email.com">
<input type="hidden" name="subject" value="Webmail">
<div class="eight-eight">
<label class="two-eight" for="name">Name</label>
<input class="six-eight" type="text" name="name" placeholder="Your name" required oninvalid="this.setCustomValidity('Please enter your Name here')" oninput="setCustomValidity('')"/>
</div>
<div class="eight-eight">
<label class="two-eight" for="name">Subject</label>
<select id="subject" name="subject">
<option value="">Choose a service..</option>
<option value="">Option 1..</option>
<option value="">Option 2..</option>
<option value="others">Others</option>
</select>
</div>
<div class="eight-eight">
<label class="two-eight" for="name">Message</label>
<textarea class="six-eight" placeholder="Your message" name="message" required oninvalid="this.setCustomValidity('May we know what your message is?')" oninput="setCustomValidity('')"/></textarea>
</div>
<div class="eight-eight">
<label class="two-eight" for="name">Email</label>
<input class="six-eight" type="mail" name="mail" placeholder="Your email address" required oninvalid="this.setCustomValidity('Please enter your Email Address here')" oninput="setCustomValidity('')"/>
</div>
<input type="submit" name = "submit" value="Send" onclick="hgsubmit()">
<input type="hidden" name="redirect" value="http://www.email.com">
</form>
</div>
</div>
Is there a different way to do it?
Here is a validator I use as part of my in house development tool. it is a server side, and part of a larger framework, but it will be ok for you.
<?php
/*
*
* #Class Name:InputValidation
* #Framework:Mlisoft MLM 4.0
* #Date Created: 18, August, 2017
* #Version: 1.0
* #Contributor: Adeniyi Anthony A <a.anthony#mlisoftinc.com>
* #mlisoftinc#gmail.com
*
*/
class InputValidation
{
/*
* ----------------------------------------------------------------
* Validate form input
* ----------------------------------------------------------------
*/
/*
* Validate form input
* #param array $data
* #param array $exceptionList
* #param array $alias
* #param array $filters
* #return array
*/
public function validateInputs(array $data, array $exceptionList = null, array $alias = null, array $filters = null)
{
if ($data == null || $data == "" || !$data || !is_array($data)) {
return array(
'status' => false,
'msg' => 'Invalid data provided',
);
}
$errorList = null;
foreach ($data as $curData => $value) {
$exceptCurrent = false;
if ($value == "") {
/*
* check if this is part of the exception
*/
if ($exceptionList !== null) {
foreach ($exceptionList as $curExcept) {
/*
* case insensitive search
*/
if ($curData == $curExcept) {
$exceptCurrent = true;
break;
}
}
}
if ($exceptCurrent === false) {
if ($alias != null && isset($alias[$curData])) {
$name = $alias[$curData];
} else {
$name = $curData;
}
$errorList[] = array(
'name' => $name,
'value' => $value,
);
}
}
/*
* finally, lets validate filters if they are passed
*/
if ($filters != null && isset($filters[$curData])) {
/*
* check the filter validations
*/
$curFilter = $filters[$curData];
/*
* go over the filter, and validate each filter
* parameter provided
*/
foreach ($curFilter as $key => $paramValue) {
if (!isset($name)) {
$name = $curData;
}
if ($key == "must") {
/*
* validate must contain the exact value provided
* can use regular expression later
*/
if (!preg_match("/" . $paramValue . "/", $value)) {
$msg = "value must contain $paramValue";
$errorList[] = array(
'name' => $name,
'value' => $value,
'msg' => $msg,
);
}
}
}
}
}
/*
* attempt tp build a long error message
*/
$msg = null;
if (isset($errorList) && $errorList !== null) {
$msg = "Invalid input. Ensure all required form field are entered<br>";
foreach ($errorList as $error) {
if (isset($error['msg'])) {
$msg = $msg . $error['name'] . " " . $error['msg'];
} else {
$msg = $msg . $error['name'] . " cannot be empty<br>";
}
}
}
/*
* return complete validation
*/
if ($errorList === null) {
return array(
'status' => true,
'msg' => 'Success',
'error' => false,
'error_list' => $errorList,
'error_msg' => null,
);
} elseif ($errorList !== null) {
return array(
'status' => false,
'msg' => 'Failed',
'error' => true,
'error_list' => $errorList,
'error_msg' => $msg,
);
}
}
}
call validation like this:
$validator = new InputValidation();
$val = $validator->validateInputs($data);
if (isset($val['error']) && $val['error'] == true) {
// do whatever
);
}
The validator also accept other optional parameters like
$exceptionList ['formField','anotherFormFiled']
use to exempt some field from validation
$alias pass as array('formField' => 'Form Filed Caption')
use to display custom some field caption
$filters as ['email' => array('must' => "#")]
use to validate input. for example email
I would like to let the form send a copy to the email address which the visitor entered into 'label' => 'Email'.
3 php files are handling the whole thing and are as fallows:
This is the PHP Form which handles the input of the HTML
<?php
require_once('form_process.php');
$form = array(
'subject' => 'Contact Form',
'heading' => 'Submission',
'success_redirect' => '',
'resources' => array(
'checkbox_checked' => 'Checked',
'checkbox_unchecked' => 'Unchecked',
'submitted_from' => 'Form submitted from website: %s',
'submitted_by' => 'Visitor IP address: %s',
'too_many_submissions' => 'Too many recent submissions from this IP',
'failed_to_send_email' => 'Failed to send email',
'invalid_reCAPTCHA_private_key' => 'Invalid reCAPTCHA private key.',
'invalid_field_type' => 'Unknown field type \'%s\'.',
'invalid_form_config' => 'Field \'%s\' has an invalid configuration.',
'unknown_method' => 'Unknown server request method'
),
'email' => array(
'from' => 'info#myurl.com',
'to' => 'info#myurl.com'
),
'fields' => array(
'custom_U8149' => array(
'order' => 1,
'type' => 'string',
'label' => 'Name',
'required' => true,
'errors' => array(
'required' => 'Field \'Name\' is required.'
)
),
'Email' => array(
'order' => 2,
'type' => 'email',
'label' => 'Email',
'required' => true,
'errors' => array(
'required' => 'Field \'Email\' is required.',
'format' => 'Field \'Email\' has an invalid email.'
)
),
'custom_U8139' => array(
'order' => 3,
'type' => 'string',
'label' => 'Message',
'required' => false,
'errors' => array(
)
)
)
);
process_form($form);
?>
This is the form_process.php
<?php
require_once('form_throttle.php');
function process_form($form) {
if ($_SERVER['REQUEST_METHOD'] != 'POST')
die(get_form_error_response($form['resources']['unknown_method']));
if (formthrottle_too_many_submissions($_SERVER['REMOTE_ADDR']))
die(get_form_error_response($form['resources']['too_many_submissions']));
// will die() if there are any errors
check_required_fields($form);
// will die() if there is a send email problem
email_form_submission($form);
}
function get_form_error_response($error) {
return get_form_response(false, array('error' => $error));
}
function get_form_response($success, $data) {
if (!is_array($data))
die('data must be array');
$status = array();
$status[$success ? 'FormResponse' : 'MusePHPFormResponse'] = array_merge(array('success' => $success), $data);
return json_serialize($status);
}
function check_required_fields($form) {
$errors = array();
foreach ($form['fields'] as $field => $properties) {
if (!$properties['required'])
continue;
if (!array_key_exists($field, $_REQUEST) || empty($_REQUEST[$field]))
array_push($errors, array('field' => $field, 'message' => $properties['errors']['required']));
else if (!check_field_value_format($form, $field, $properties))
array_push($errors, array('field' => $field, 'message' => $properties['errors']['format']));
}
if (!empty($errors))
die(get_form_error_response(array('fields' => $errors)));
}
function check_field_value_format($form, $field, $properties) {
$value = get_form_field_value($field, $properties, $form['resources'], false);
switch($properties['type']) {
case 'checkbox':
case 'string':
case 'captcha':
// no format to validate for those fields
return true;
case 'checkboxgroup':
if (!array_key_exists('optionItems', $properties))
die(get_form_error_response(sprintf($form['resources']['invalid_form_config'], $properties['label'])));
// If the value received is not an array, treat it as invalid format
if (!isset($value))
return false;
// Check each option to see if it is a valid value
foreach($value as $checkboxValue) {
if (!in_array($checkboxValue, $properties['optionItems']))
return false;
}
return true;
case 'radiogroup':
if (!array_key_exists('optionItems', $properties))
die(get_form_error_response(sprintf($form['resources']['invalid_form_config'], $properties['label'])));
//check list of real radio values
return in_array($value, $properties['optionItems']);
case 'recaptcha':
if (!array_key_exists('recaptcha', $form) || !array_key_exists('private_key', $form['recaptcha']) || empty($form['recaptcha']['private_key']))
die(get_form_error_response($form['resources']['invalid_reCAPTCHA_private_key']));
$resp = recaptcha_check_answer($form['recaptcha']['private_key'], $_SERVER["REMOTE_ADDR"], $_POST["recaptcha_challenge_field"], $_POST["recaptcha_response_field"]);
return $resp->is_valid;
case 'email':
return 1 == preg_match('/^[a-z0-9!#$%&\'*+\/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&\'*+\/=?^_`{|}~-]+)*#(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i', $value);
case 'radio': // never validate the format of a single radio element; only the group gets validated
default:
die(get_form_error_response(sprintf($form['resources']['invalid_field_type'], $properties['type'])));
}
}
function email_form_submission($form) {
if(!defined('PHP_EOL'))
define('PHP_EOL', '\r\n');
$form_email = ((array_key_exists('Email', $_REQUEST) && !empty($_REQUEST['Email'])) ? cleanup_email($_REQUEST['Email']) : '');
$to = $form['email']['to'];
$subject = $form['subject'];
$message = get_email_body($subject, $form['heading'], $form['fields'], $form['resources']);
$headers = get_email_headers($to, $form_email);
$sent = #mail($to, $subject, $message, $headers);
if(!$sent)
die(get_form_error_response($form['resources']['failed_to_send_email']));
$success_data = array(
'redirect' => $form['success_redirect']
);
echo get_form_response(true, $success_data);
}
function get_email_headers($to_email, $form_email) {
$headers = 'From: ' . $to_email . PHP_EOL;
$headers .= 'Reply-To: ' . $form_email . PHP_EOL;
$headers .= 'X-Mailer: Adobe Muse CC 2015.0.2.310 with PHP' . PHP_EOL;
$headers .= 'Content-type: text/html; charset=utf-8' . PHP_EOL;
return $headers;
}
function get_email_body($subject, $heading, $fields, $resources) {
$message = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">';
$message .= '<html xmlns="http://www.w3.org/1999/xhtml">';
$message .= '<head><meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/><title>' . encode_for_form($subject) . '</title></head>';
$message .= '<body style="background-color: #ffffff; color: #000000; font-style: normal; font-variant: normal; font-weight: normal; font-size: 12px; line-height: 18px; font-family: helvetica, arial, verdana, sans-serif;">';
$message .= '<h2 style="background-color: #eeeeee;">' . $heading . '</h2>';
$message .= '<table cellspacing="0" cellpadding="0" width="100%" style="background-color: #ffffff;">';
$sorted_fields = array();
foreach ($fields as $field => $properties) {
// Skip reCAPTCHA from email submission
if ('recaptcha' == $properties['type'])
continue;
array_push($sorted_fields, array('field' => $field, 'properties' => $properties));
}
// sort fields
usort($sorted_fields, 'field_comparer');
foreach ($sorted_fields as $field_wrapper)
$message .= '<tr><td valign="top" style="background-color: #ffffff;"><b>' . encode_for_form($field_wrapper['properties']['label']) . ':</b></td><td>' . get_form_field_value($field_wrapper['field'], $field_wrapper['properties'], $resources, true) . '</td></tr>';
$message .= '</table>';
$message .= '<br/><br/>';
$message .= '<div style="background-color: #eeeeee; font-size: 10px; line-height: 11px;">' . sprintf($resources['submitted_from'], encode_for_form($_SERVER['SERVER_NAME'])) . '</div>';
$message .= '<div style="background-color: #eeeeee; font-size: 10px; line-height: 11px;">' . sprintf($resources['submitted_by'], encode_for_form($_SERVER['REMOTE_ADDR'])) . '</div>';
$message .= '</body></html>';
return cleanup_message($message);
}
function field_comparer($field1, $field2) {
if ($field1['properties']['order'] == $field2['properties']['order'])
return 0;
return (($field1['properties']['order'] < $field2['properties']['order']) ? -1 : 1);
}
function is_assoc_array($arr) {
if (!is_array($arr))
return false;
$keys = array_keys($arr);
foreach (array_keys($arr) as $key)
if (is_string($key)) return true;
return false;
}
function json_serialize($data) {
if (is_assoc_array($data)) {
$json = array();
foreach ($data as $key => $value)
array_push($json, '"' . $key . '": ' . json_serialize($value));
return '{' . implode(', ', $json) . '}';
}
if (is_array($data)) {
$json = array();
foreach ($data as $value)
array_push($json, json_serialize($value));
return '[' . implode(', ', $json) . ']';
}
if (is_int($data) || is_float($data))
return $data;
if (is_bool($data))
return $data ? 'true' : 'false';
return '"' . encode_for_json($data) . '"';
}
function encode_for_json($value) {
return preg_replace(array('/([\'"\\t\\\\])/i', '/\\r/i', '/\\n/i'), array('\\\\$1', '\\r', '\\n'), $value);
}
function encode_for_form($text) {
$text = stripslashes($text);
return htmlentities($text, ENT_QUOTES, 'UTF-8');// need ENT_QUOTES or webpro.js jQuery.parseJSON fails
}
function get_form_field_value($field, $properties, $resources, $forOutput) {
$value = $_REQUEST[$field];
switch($properties['type']) {
case 'checkbox':
return (($value == '1' || $value == 'true') ? $resources['checkbox_checked'] : $resources['checkbox_unchecked']);
case 'checkboxgroup':
if (!is_array($value))
return NULL;
$outputValue = array();
foreach ($value as $checkboxValue)
array_push($outputValue, $forOutput ? encode_for_form($checkboxValue) : stripslashes($checkboxValue));
if ($forOutput)
$outputValue = implode(', ', $outputValue);
return $outputValue;
case 'radiogroup':
return ($forOutput ? encode_for_form($value) : stripslashes($value));
case 'string':
case 'captcha':
case 'recaptcha':
case 'email':
return encode_for_form($value);
case 'radio': // never validate the format of a single radio element; only the group gets validated
default:
die(get_form_error_response(sprintf($resources['invalid_field_type'], $properties['type'])));
}
}
function cleanup_email($email) {
$email = encode_for_form($email);
$email = preg_replace('=((<CR>|<LF>|0x0A/%0A|0x0D/%0D|\\n|\\r)\S).*=i', null, $email);
return $email;
}
function cleanup_message($message) {
$message = wordwrap($message, 70, "\r\n");
return $message;
}
?>
This is the form_throttle.php
<?php
function formthrottle_check()
{
if (!is_writable('.'))
{
return '8';
}
try
{
if (in_array("sqlite",PDO::getAvailableDrivers(),TRUE))
{
$db = new PDO('sqlite:muse-throttle-db.sqlite3');
if ( file_exists('muse-throttle-db') )
{
unlink('muse-throttle-db');
}
}
else if (function_exists("sqlite_open"))
{
$db = new PDO('sqlite2:muse-throttle-db');
if ( file_exists('muse-throttle-db.sqlite3') )
{
unlink('muse-throttle-db.sqlite3');
}
}
}
catch( PDOException $Exception ) {
return '9';
}
$retCode ='5';
if ($db)
{
$res = $db->query("SELECT 1 FROM sqlite_master WHERE type='table' AND name='Submission_History';");
if (!$res or $res->fetchColumn() == 0)
{
$created = $db->exec("CREATE TABLE Submission_History (IP VARCHAR(39), Submission_Date TIMESTAMP)");
if($created == 0)
{
$created = $db->exec("INSERT INTO Submission_History (IP,Submission_Date) VALUES ('256.256.256.256', DATETIME('now'))");
}
if ($created != 1)
{
$retCode = '2';
}
}
if($retCode == '5')
{
$res = $db->query("SELECT COUNT(1) FROM Submission_History;");
if ($res && $res->fetchColumn() > 0)
{
$retCode = '0';
}
else
$retCode = '3';
}
// Close file db connection
$db = null;
}
else
$retCode = '4';
return $retCode;
}
function formthrottle_too_many_submissions($ip)
{
$tooManySubmissions = false;
try
{
if (in_array("sqlite",PDO::getAvailableDrivers(),TRUE))
{
$db = new PDO('sqlite:muse-throttle-db.sqlite3');
}
else if (function_exists("sqlite_open"))
{
$db = new PDO('sqlite2:muse-throttle-db');
}
}
catch( PDOException $Exception ) {
return $tooManySubmissions;
}
if ($db)
{
$res = $db->query("SELECT 1 FROM sqlite_master WHERE type='table' AND name='Submission_History';");
if (!$res or $res->fetchColumn() == 0)
{
$db->exec("CREATE TABLE Submission_History (IP VARCHAR(39), Submission_Date TIMESTAMP)");
}
$db->exec("DELETE FROM Submission_History WHERE Submission_Date < DATETIME('now','-2 hours')");
$stmt = $db->prepare("INSERT INTO Submission_History (IP,Submission_Date) VALUES (:ip, DATETIME('now'))");
$stmt->bindParam(':ip', $ip);
$stmt->execute();
$stmt->closeCursor();
$stmt = $db->prepare("SELECT COUNT(1) FROM Submission_History WHERE IP = :ip;");
$stmt->bindParam(':ip', $ip);
$stmt->execute();
if ($stmt->fetchColumn() > 25)
$tooManySubmissions = true;
// Close file db connection
$db = null;
}
return $tooManySubmissions;
}
?>
I'm trying to create a simple contact form in HTML with PHP script for my website. Internet is full of examples, but they usually are too simple or too complicated.
Here's my form in HTML and I need PHP script for it.
<form action="send.php" method="POST" id="form">
<label for="latitude">Lat. °N:</label>
<input id="latitude" name="latitude" type="text" />
<label for="longitude">Long. °E:</label>
<input id="longitude" name="longitude" type="text" />
<label for="desc">Description:</label>
<textarea style="resize:none" name="desc" cols="45" rows="5"></textarea>
<label for="mail">E-mail:</label>
<input type="text" name="mail" /><br>
<input type="submit" name="submit" value="Send">
</form>
It should contain charset=utf-8 to display all of my language's diacritics in a message.
It should have a validation if ALL fields are not empty. E-mail validation is not needed.
It should inform in a very simple way Message send! or Error, try again.
#EWit is right... You can't really use Stack Overflow like this. However, the PHP below should work. Try and pull it apart so you can learn from it. Cheers
<?PHP
define('kOptional', true);
define('kMandatory', false);
error_reporting(E_ERROR | E_WARNING | E_PARSE);
ini_set('track_errors', true);
function DoStripSlashes($fieldValue) {
if ( function_exists( 'get_magic_quotes_gpc' ) && get_magic_quotes_gpc() ) {
if (is_array($fieldValue) ) {
return array_map('DoStripSlashes', $fieldValue);
} else {
return trim(stripslashes($fieldValue));
}
} else {
return $fieldValue;
}
}
function FilterCChars($theString) {
return preg_replace('/[\x00-\x1F]/', '', $theString);
}
function CheckEmail($email, $optional) {
if ( (strlen($email) == 0) && ($optional === kOptional) ) {
return true;
} elseif ( preg_match("/^([\w\!\#$\%\&\'\*\+\-\/\=\?\^\`{\|\}\~]+\.)*[\w\!\#$\%\&\'\*\+\-\/\=\?\^\`{\|\}\~]+#((((([a-z0-9]{1}[a-z0-9\-]{0,62}[a-z0-9]{1})|[a-z])\.)+[a-z]{2,6})|(\d{1,3}\.){3}\d{1,3}(\:\d{1,5})?)$/i", $email) == 1 ) {
return true;
} else {
return false;
}
}
if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$clientIP = $_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
$clientIP = $_SERVER['REMOTE_ADDR'];
}
$FTGlatitude = DoStripSlashes( $_POST['latitude'] );
$FTGlongitude = DoStripSlashes( $_POST['longitude'] );
$FTGdesc = DoStripSlashes( $_POST['desc'] );
$FTGmail = DoStripSlashes( $_POST['mail'] );
$FTGsubmit = DoStripSlashes( $_POST['submit'] );
$validationFailed = false;
if (!CheckEmail($FTGmail, kMandatory)) {
$FTGErrorMessage['mail'] = 'Please enter a valid email address';
$validationFailed = true;
}
if ($validationFailed === true) {
$errorPage = '<html><head><meta http-equiv="content-type" content="text/html; charset=utf-8" /><title>Error</title></head><body>Errors found: <!--VALIDATIONERROR--></body></html>';
$errorPage = str_replace('<!--FIELDVALUE:latitude-->', $FTGlatitude, $errorPage);
$errorPage = str_replace('<!--FIELDVALUE:longitude-->', $FTGlongitude, $errorPage);
$errorPage = str_replace('<!--FIELDVALUE:desc-->', $FTGdesc, $errorPage);
$errorPage = str_replace('<!--FIELDVALUE:mail-->', $FTGmail, $errorPage);
$errorPage = str_replace('<!--FIELDVALUE:submit-->', $FTGsubmit, $errorPage);
$errorPage = str_replace('<!--ERRORMSG:mail-->', $FTGErrorMessage['mail'], $errorPage);
$errorList = #implode("<br />\n", $FTGErrorMessage);
$errorPage = str_replace('<!--VALIDATIONERROR-->', $errorList, $errorPage);
echo $errorPage;
}
if ( $validationFailed === false ) {
$emailSubject = FilterCChars("Website Contact");
$emailBody = chunk_split( base64_encode( "<html>\n"
. "<head>\n"
. "<title></title>\n"
. "</head>\n"
. "<body>\n"
. "Latitude : $FTGlatitude<br />\n"
. "Longitude : $FTGlongitude<br />\n"
. "Desc : " . nl2br( $FTGdesc ) . "<br />\n"
. "Mail : $FTGmail<br />\n"
. "Submit : $FTGsubmit<br />\n"
. "</body>\n"
. "</html>\n"
. "" ) )
. "\n";
$emailTo = 'Contact <your#email.com>';
$emailFrom = FilterCChars("$FTGmail");
$emailHeader = "From: $emailFrom\n"
. "MIME-Version: 1.0\n"
. "Content-Type: text/html; charset=\"UTF-8\"\n"
. "Content-Transfer-Encoding: base64\n"
. "\n";
mail($emailTo, $emailSubject, $emailBody, $emailHeader);
$successPage = '<html><head><meta http-equiv="content-type" content="text/html; charset=utf-8" /><title>Success</title></head><body>Form submitted successfully. It will be reviewed soon.</body></html>';
$successPage = str_replace('<!--FIELDVALUE:latitude-->', $FTGlatitude, $successPage);
$successPage = str_replace('<!--FIELDVALUE:longitude-->', $FTGlongitude, $successPage);
$successPage = str_replace('<!--FIELDVALUE:desc-->', $FTGdesc, $successPage);
$successPage = str_replace('<!--FIELDVALUE:mail-->', $FTGmail, $successPage);
$successPage = str_replace('<!--FIELDVALUE:submit-->', $FTGsubmit, $successPage);
echo $successPage;
}
?>
I am trying to add a honeypot field to my form and every thing I have researched I cannot understand where to place the code. Any help would be appreciated. Here is what I have:
<div class="hide">
<label for="spam">What is two plus two?</label>
<input name="spam" type="text" size="4" id="spam">
</div>
Here is the css:
.hide {display: none;}
Here is the .php that I am trying to incorporate in my .php file:
$spa = $_POST["spam"];
if (!empty($spa) && !($spa == "4" || $spa == "four")) {
echo "You failed the bot test!";
exit ();
}
Here is the .php file itself:
<?php
class contactForm{
function contactForm($cfg)
{
$this->cfg['email_address'] = isset($cfg['email_address'])?$cfg['email_address']:'';
// =?UTF-8?B? required to avoid bad character encoding in the From field
// é (keeps utf-8 encoding in the file)
$this->cfg['email_from'] = (isset($cfg['email_from']) && $cfg['email_from'])?'=?UTF-8?B?'.base64_encode($cfg['email_from']).'?=':$this->cfg['email_address'];
$this->cfg['email_address_cc'] = isset($cfg['email_address_cc'])?$cfg['email_address_cc']:'';
$this->cfg['email_address_bcc'] = isset($cfg['email_address_bcc'])?$cfg['email_address_bcc']:'';
$this->cfg['timezone'] = isset($cfg['timezone'])?$cfg['timezone']:'';
$this->cfg['adminnotification_subject'] = isset($cfg['adminnotification_subject'])?$cfg['adminnotification_subject']:'';
$this->cfg['usernotification_insertformdata'] = isset($cfg['usernotification_insertformdata'])?$cfg['usernotification_insertformdata']:'';
$this->cfg['usernotification_inputid'] = isset($cfg['usernotification_inputid'])?$cfg['usernotification_inputid']:'';
$this->cfg['usernotification_subject'] = isset($cfg['usernotification_subject'])?$cfg['usernotification_subject']:'';
$this->cfg['usernotification_message'] = isset($cfg['usernotification_message'])?preg_replace('#<br(\s*)/>|<br(\s*)>#i', "\r\n",$cfg['usernotification_message']):'';
$this->cfg['form_name'] = isset($cfg['form_name'])?$cfg['form_name']:'';
$this->cfg['form_errormessage_captcha'] = isset($cfg['form_errormessage_captcha'])?$cfg['form_errormessage_captcha']:'';
$this->cfg['form_errormessage_emptyfield'] = isset($cfg['form_errormessage_emptyfield'])?$cfg['form_errormessage_emptyfield']:'';
$this->cfg['form_errormessage_invalidemailaddress'] = isset($cfg['form_errormessage_invalidemailaddress'])?$cfg['form_errormessage_invalidemailaddress']:'';
$this->cfg['form_validationmessage'] = isset($cfg['form_validationmessage'])?$cfg['form_validationmessage']:'';
$this->cfg['form_redirecturl'] = isset($cfg['form_redirecturl'])?$cfg['form_redirecturl']:'';
$this->dash_line = '--------------------------------------------------------------';
$this->mail_content_type_format = 'plaintext'; // html
if($this->mail_content_type_format == 'plaintext')
{
$this->mail_content_type_format_charset = 'Content-type: text/plain; charset=utf-8';
$this->mail_line_break = "\r\n";
}
if($this->mail_content_type_format == 'html')
{
$this->mail_content_type_format_charset = 'Content-type: text/html; charset=utf-8';
$this->mail_line_break = "<br />";
}
/**
* USER NOTIFICATION MAIL FORMAT
*/
$this->cfg['usernotification_format'] = isset($cfg['usernotification_format'])?$cfg['usernotification_format']:'';
if($this->cfg['usernotification_format'] == 'plaintext')
{
$this->mail_content_type_format_charset_usernotification = 'Content-type: text/plain; charset=utf-8';
$this->mail_line_break_usernotification = "\r\n";
}
if($this->cfg['usernotification_format'] == 'html')
{
$this->mail_content_type_format_charset_usernotification = 'Content-type: text/html; charset=utf-8';
$this->mail_line_break_usernotification = "<br />";
}
$this->merge_post_index = 0;
$this->demo = 0;
$this->envato_link = '';
}
function sendMail($param)
{
$count_files_to_attach = 0;
// grab and insert the form URL in the notification message
$form_url = (#$_SERVER['HTTPS'] == 'on') ? 'https://' : 'http://';
if($_SERVER['SERVER_PORT'] != '80')
{
$form_url .= $_SERVER['SERVER_NAME'].':'.$_SERVER['SERVER_PORT'].rawurlencode($_SERVER['SCRIPT_NAME']);
}
else
{
$form_url .= $_SERVER['SERVER_NAME'].rawurlencode($_SERVER['SCRIPT_NAME']);
}
$form_url = str_replace('%2F', '/', $form_url);
$form_url_exp = explode('/', $form_url);
// remove contactform/inc/form-validation.php
$pattern_slash = $form_url_exp[count($form_url_exp)-3].'/'.$form_url_exp[count($form_url_exp)-2].'/'.$form_url_exp[count($form_url_exp)-1];
$form_url = str_replace($pattern_slash, '', $form_url);
if($this->cfg['timezone'])
{
date_default_timezone_set($this->cfg['timezone']);
}
// g:i A | 01:37 AM
// G:i | 13:37
$mail_body = $this->cfg['adminnotification_subject'].': '.#date("F jS, Y, G:i")
.$this->mail_line_break.$this->mail_line_break.$this->cfg['form_name']
.$this->mail_line_break.$this->mail_line_break.'Form URL: '
.$this->mail_line_break.$form_url
.$this->mail_line_break.$this->dash_line;
if($this->merge_post)
{
foreach($this->merge_post as $value)
{
if(
isset($value['element_type']) && $value['element_type'] == 'upload'
&& isset($value['filename']) && $value['filename']
)
{
if( isset($value['deletefile']) && ($value['deletefile'] == 1 || $value['deletefile'] == 2) )
{
$count_files_to_attach++;
}
$explode_requesturi = explode('/',$_SERVER['REQUEST_URI']);
//print_r($explode_requesturi);
$explode_requesturi = explode('/',$_SERVER['SCRIPT_NAME']);
//print_r($explode_requesturi);
$inc_form_validation = $explode_requesturi[count($explode_requesturi)-2].'/'.$explode_requesturi[count($explode_requesturi)-1] ;
$install_dir = str_replace($inc_form_validation,'',$_SERVER['SCRIPT_NAME']);
$mail_body .= $this->mail_line_break.$this->mail_line_break.$value['elementlabel_value'].': '.$value['element_value'];
// No file link if we delete the file after the upload
// 1: File Attachment + Download Link
// 2: File Attachment Only
if( isset($value['deletefile']) && ($value['deletefile'] == 1 || $value['deletefile'] == 3) )
{
$mail_body .= $this->mail_line_break
.'http://'.$_SERVER['SERVER_NAME']
.str_replace('%2F', '/', rawurlencode($install_dir.'upload/'.$value['element_value']));
}
}
else{
$mail_body .= $this->mail_line_break.$this->mail_line_break.$value['elementlabel_value'].': '.$value['element_value'];
}
}
}
$mail_body .= $this->mail_line_break.$this->mail_line_break.$this->dash_line;
$mail_body .= $this->mail_line_break.'IP address: '.$_SERVER['REMOTE_ADDR'];
$mail_body .= $this->mail_line_break.'Host: '.gethostbyaddr($_SERVER['REMOTE_ADDR']);
if(preg_match('#html#', $this->mail_content_type_format_charset))
{
$mail_body = nl2br($mail_body);
}
if($this->demo != 1)
{
// for the admin: if the user provides his email address, it will appear in the "from" field
$param['reply_emailaddress'] = (isset($param['reply_emailaddress']) && $param['reply_emailaddress'])?$param['reply_emailaddress']:$this->cfg['email_address'];
// for the admin: if the user provides his email address, it will appear in the "reply-to" field
$replyto_name = $param['reply_emailaddress']?$param['reply_emailaddress']:'';
$replyto_address = $param['reply_emailaddress']?$param['reply_emailaddress']:'';
$mailheaders_options = array(
'from'=>array('name'=>$param['reply_emailaddress'], 'address'=>$param['reply_emailaddress']),
'replyto'=>array('name'=>$replyto_name, 'address'=>$replyto_address),
'cc'=>array('address'=>$this->cfg['email_address_cc']),
'bcc'=>array('address'=>$this->cfg['email_address_bcc'])
);
$mailheaders = $this->getMailHeaders($mailheaders_options);
//if(!isset($param['uploads']) || !$param['uploads'])
if(!$count_files_to_attach)
{
$mailheaders .= $this->mail_content_type_format_charset."\r\n";
$mailmessage = $mail_body;
} else
{
// boundary
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
// headers for attachment
$mailheaders .= "MIME-Version: 1.0\n"
."Content-Type: multipart/mixed;\n"
." boundary=\"{$mime_boundary}\"";
// multipart boundary
$mailmessage = "This is a multi-part message in MIME format.\n\n"
."--{$mime_boundary}\n"
.$this->mail_content_type_format_charset."\n"
."Content-Transfer-Encoding: 7bit\n\n"
.$mail_body
."\n\n";
$mailmessage .= "--{$mime_boundary}\n";
// preparing attachments
$count_attached_file = 0;
foreach($this->merge_post as $value)
{
if(
isset($value['element_type']) && $value['element_type'] == 'upload'
&& isset($value['filename']) && $value['filename']
&& isset($value['deletefile']) && ($value['deletefile'] == 1 || $value['deletefile'] == 2)
)
{
$count_attached_file++;
$file = fopen('../upload/'.$value['filename'],"rb");
$data = fread($file,filesize('../upload/'.$value['filename']));
fclose($file);
$data = chunk_split(base64_encode($data));
$mailmessage .= 'Content-Type: {"application/octet-stream"};'."\n" . ' name="'.$value['filename'].'"'."\n"
.'Content-Disposition: attachment;'."\n" . ' filename="'.$value['filename'].'"'."\n"
.'Content-Transfer-Encoding: base64'."\n\n" . $data . "\n\n";
// "--" must be added for the last file, or an empty file will be also attached in the message
if($count_attached_file == $count_files_to_attach)
{
$mailmessage .= "--{$mime_boundary}--\n";
} else{
$mailmessage .= "--{$mime_boundary}\n";
}
// delete attached file?
// this is different from deleting the file when the user deletes the file himself in the from: check form-validation.php for this (in form-validation.php because the file must be deleted even if sendMail() is not called - when there are errors for example)
if(isset($value['deletefile']) && $value['deletefile'] == 2)
{
#unlink('../upload/'.$value['filename']);
}
}
} // foreach
} // if(!$count_files_to_attach)
#mail($this->cfg['email_address'], $this->cfg['adminnotification_subject'], $mailmessage, $mailheaders);
}
}
function sendMailReceipt($value)
{
if($this->demo != 1)
{
$mailheaders_options = array(
'from'=>array('name'=>$this->cfg['email_from'], 'address'=>$this->cfg['email_address']),
'replyto'=>array('name'=>$this->cfg['email_from'], 'address'=>$this->cfg['email_address'])
);
$mailheaders = $this->getMailHeaders($mailheaders_options)
.$this->mail_content_type_format_charset_usernotification."\r\n"
;
$mail_body = '';
$mail_body .= $this->cfg['usernotification_message'];
if($this->cfg['usernotification_insertformdata'])
{
$mail_body .= $this->mail_line_break_usernotification."--------------------------------------------------------";
foreach($this->merge_post as $form_data)
{
$mail_body .= $this->mail_line_break_usernotification.$this->mail_line_break_usernotification.$form_data['elementlabel_value'].': '.$form_data['element_value'];
}
}
if(preg_match('#html#', $this->mail_content_type_format_charset_usernotification))
{
$mail_body = nl2br($mail_body);
}
#mail($value['email_address'], $this->cfg['usernotification_subject'], $mail_body, $mailheaders);
}
}
function mergePost($value)
{
$this->merge_post[$this->merge_post_index]['element_id'] = $value['element_id'];
$this->merge_post[$this->merge_post_index]['element_value'] = $this->quote_smart(trim($value['element_value']));
$this->merge_post[$this->merge_post_index]['elementlabel_value'] = $this->quote_smart(trim($value['elementlabel_value']));
$this->merge_post[$this->merge_post_index]['elementlabel_id'] = $this->quote_smart(trim($value['elementlabel_id']));
if(isset($value['element_type']) && $value['element_type'])
{ // if element_type == upload, we add the download link in the mail body message
$this->merge_post[$this->merge_post_index]['element_type'] = trim($value['element_type']);
}
if(isset($value['filename']) && $value['filename'])
{
$this->merge_post[$this->merge_post_index]['filename'] = $this->quote_smart(trim($value['filename']));
}
if(isset($value['deletefile']) && $value['deletefile'])
{
$this->merge_post[$this->merge_post_index]['deletefile'] = trim($value['deletefile']);
}
$this->merge_post_index++;
}
function isEmail($email)
{
$atom = '[-a-z0-9\\_]'; // authorized caracters before #
$domain = '([a-z0-9]([-a-z0-9]*[a-z0-9]+)?)'; // authorized caracters after #
$regex = '/^' . $atom . '+' .
'(\.' . $atom . '+)*' .
'#' .
'(' . $domain . '{1,63}\.)+' .
$domain . '{2,63}$/i';
// test de l'adresse e-mail
return preg_match($regex, trim($email)) ? 1 : 0;
}
function quote_smart($value)
{
if(get_magic_quotes_gpc())
{
$value = stripslashes($value);
}
return $value;
}
function getMailHeaders($mailheaders_options)
{
$mailheaders_options['from']['name'] = isset($mailheaders_options['from']['name'])?$mailheaders_options['from']['name']:$mailheaders_options['from']['address'];
$mailheaders_options['cc']['address'] = isset($mailheaders_options['cc']['address'])?$mailheaders_options['cc']['address']:'';
$mailheaders_options['bcc']['address'] = isset($mailheaders_options['bcc']['address'])?$mailheaders_options['bcc']['address']:'';
$from_name = $mailheaders_options['from']['name']?$mailheaders_options['from']['name']:$mailheaders_options['from']['address'];
if($this->isEmail($from_name))
{
// From: user#domain.com <user#domain.com> is invalid => user#domain.com
$mail_header_from = 'From: '.$from_name."\r\n";
$mail_header_replyto = 'Reply-To: '.$from_name."\r\n";
} else
{
$mail_header_from = 'From: '.$from_name.'<'.$mailheaders_options['from']['address'].'>'."\r\n";
$mail_header_replyto = 'Reply-To: '.$from_name.'<'.$mailheaders_options['from']['address'].'>'."\r\n";
}
$mail_header_cc = '';
if($mailheaders_options['cc']['address'])
{
$explode_email = explode(',', $mailheaders_options['cc']['address']);
$cc = '';
foreach($explode_email as $email_value)
{
$cc .= $email_value.",";
}
$mail_header_cc .= 'Cc: '.substr($cc, 0, -1)."\r\n";
}
$mail_header_bcc = '';
if($mailheaders_options['bcc']['address'])
{
$explode_email = explode(',', $mailheaders_options['bcc']['address']);
$bcc = '';
foreach($explode_email as $email_value)
{
$bcc .= $email_value.",";
}
$mail_header_bcc .= 'Bcc: '.substr($bcc, 0, -1)."\r\n";
}
$mailheaders = $mail_header_from
.$mail_header_cc
.$mail_header_bcc
.$mail_header_replyto
.'MIME-Version: 1.0'."\r\n"
.'X-Mailer: PHP/'.phpversion()."\r\n"
;
/*
Examples of headers that should work would be:
From: user#domain.com will work
From: "user" <user#domain.com>
Examples of headers that will NOT work:
From: "user#domain.com"
From: user # domain.com
From: user#domain.com <user#domain.com>
*/
// echo $mailheaders;
return($mailheaders);
}
}
/**
* NO SPACES AFTER THIS LINE TO PREVENT
* Warning: Cannot modify header information
*/
?>
The idea of a honeypod is that most of the spambots can't execute javascript. So you do the folowwing:
Add a field with a spam question (as you did)
Fill in the correct value with javascript
Hide the field with javascript
Check the answer from the submitted form against the correct answer in the form processing PHP script
So you ensure that someone who has javascript disabled (like a spambot) sees the input field and can insert the answer to your question manually.
All this points implemented could look like this:
<?php
$formErrorMsgs = array();
if(isset($_GET['send'])) {
if(!isset($_POST['byebye_answer']) || $_POST['byebye_answer'] != 'stackoverflow')
$formErrorMsgs[] = 'Please enter the correct answer for the antispam question';
// all the other checks for the form input
if(count($formErrorMsgs) <= 0) {
// do the database insert or whatever here
// redirect to another page or something like that afterwards
}
}
?>
<form method="post" action="?send">
<?php echo (count($formErrorMsgs) > 0)?'<ul><li>' , implode('</li><li>', $formErrorMsgs) , '</li></ul>':null; ?>
<!-- all the regular input fields -->
<dl class="byebye">
<dt><label for="byebye-answer">Type in <b>stackoverflow</b></label></dt>
<dd><input type="text" id="byebye-answer" name="byebye_answer"></dd>
</dl>
</form>
<script>
// if you're using jQuery do this
(function() {
$('#byebye-answer').val('stackoverflow');
$('.byebye').hide();
})();
</script>
I'm building a PHP registration system. It will send a notification email to me if there's a new user register to my website. But the problem is, if the user doesn't enter anything, it will send a email to me also. How do I overcome this issue?
This is the validation part.
/*Validation Begins*/
if(empty($_POST) === false) {
$required_fields = array('school_name', 'mailing_address', 'postcode', 'courier_address', 'courier_postcode', 'courier_postcode', 'phonenumber', 'faxnumber', 'email', 'website', 'principal_fullname', 'principal_phonenumber', 'principal_email');
foreach($_POST as $key=>$value){
if(empty($value) && in_array($key, $required_fields) === true){
mysql_close();
?>
<script type="text/javascript">
alert("Fields marked with an asterisk are required");
history.back();
</script>
<?php
}
}
Below is the insertion function and the mail function.
function register_school($register_data){
$fields = '`' . implode('`, `', array_keys($register_data)) . '`';
$data = '\'' . implode('\', \'', $register_data) . '\'';
mysql_query("INSERT INTO `schools_info` ($fields) VALUES ($data)");
?>
<script type='text/javascript'>
alert("Registration Successful!"); window.location.href = '/registration-success/';
</script>
<?php
$schoolname = $_POST['school_name'];
$mailing_address = $_POST['mailing_address'];
$postcode = $_POST['postcode'];
$courier_address = $_POST['courier_address'];
$phonenumber = $_POST['courier_postcode'];
$faxnumber = $_POST['faxnumber'];
$email = $_POST['email'];
$website = $_POST['website'];
$principal_fullname = $_POST['principal_fullname'];
$principal_phonenumber = $_POST['principal_phonenumber'];
$principal_email = $_POST['principal_email'];
$to = "example#hotmail.com";
$subject = "New Registered School";
$message = "School Name: $schoolname\r\nSchool Address: $mailing_address\r\nPostcode: $postcode\r\nCourier Address: $courier_address\r\nCourier Postcode: $courier_postcode\r\nPhone Number: $phonenumber\r\nFax Number: $faxnumber\r\nEmail: $email\r\nWebsite: $website\r\nPrincipal Name: $principal_fullname\r\nPrincipal Phone Number: $principal_phonenumber\r\nPrincipal Email: $principal_email";
$from = "testing.com";
$headers = "From:" . $from;
mail($to,$subject,$message,$headers);
}
Register School
if(empty($_POST) === false){
$register_data = array(
'school_name' => $_POST['school_name'],
'mailing_address' => $_POST['mailing_address'],
'postcode' => $_POST['postcode'],
'courier_address' => $_POST['courier_address'],
'courier_postcode' => $_POST['courier_postcode'],
'phonenumber' => $_POST['phonenumber'],
'faxnumber' => $_POST['faxnumber'],
'email' => $_POST['email'],
'website' => $_POST['website'],
'principal_fullname' => $_POST['principal_fullname'],
'principal_phonenumber' => $_POST['principal_phonenumber'],
'principal_email' => $_POST['principal_email'],
'CScoor' => $_POST['CScoor'],
'CS_email' => $_POST['CS_email'],
'CS_phone' => $_POST['CS_phone'],
'Engcoor' => $_POST['Engcoor'],
'Eng_email' => $_POST['Eng_email'],
'Eng_phone' => $_POST['Eng_phone'],
'Mcoor' => $_POST['Mcoor'],
'M_email' => $_POST['M_email'],
'M_phone' => $_POST['M_phone'],
'Sccoor' => $_POST['Sccoor'],
'Sc_email' => $_POST['Sc_email'],
'Sc_phone' => $_POST['Sc_phone']
);
register_school($register_data);
mysql_close();
}
Before the part:
$to = "example#hotmail.com";
$subject = "New Registered School";
$message = "School Name: $schoolname\r\nSchool Address: $mailing_address\r\nPostcode: $postcode\r\nCourier Address: $courier_address\r\nCourier Postcode: $courier_postcode\r\nPhone Number: $phonenumber\r\nFax Number: $faxnumber\r\nEmail: $email\r\nWebsite: $website\r\nPrincipal Name: $principal_fullname\r\nPrincipal Phone Number: $principal_phonenumber\r\nPrincipal Email: $principal_email";
$from = "testing.com";
$headers = "From:" . $from;
mail($to,$subject,$message,$headers);
begins. Check every variable if it is empty or not:
// Edit: Sorry didn't see that you have an array about the values. Then you can make it something like this:
$success = true;
foreach($register_data as $data) {
if (empty($_POST[$data])) {
$success = false;
break;
}
}
if ($success == true) {
//then mail
}
if(empty($_POST) === false) {
$required_fields = array('school_name', 'mailing_address', 'postcode', 'courier_address', 'courier_postcode', 'courier_postcode', 'phonenumber', 'faxnumber', 'email', 'website', 'principal_fullname', 'principal_phonenumber', 'principal_email');
$flag = TRUE;
foreach($_POST as $key=>$value){
if(empty($value) && in_array($key, $required_fields) === true){
mysql_close();
$flag = FALSE;
?>
<script type="text/javascript">
alert("Fields marked with an asterisk are required");
history.back();
</script>
<?php
} // end second if
} //end foreach
if ($flag == TRUE){
$register_data = array(.....); //all $_POST value assign here
register_school($register_data);}
} //end first if