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;
}
?>
Related
I have uploaded a cv successfully from a career page . Now i want to send this in email.
Upload part
if ($_FILES['filecv']['name'] != "") {
$sqldata['att_ment'] = uploadCVFile($_FILES['filecv']);
} else {
$sqldata['att_ment'] = '';
}
CV is uploaded successfully.
uploadCVFile function
function uploadCVFile($uploadedfile)
{
if (!function_exists('wp_handle_upload'))
require_once (ABSPATH . 'wp-admin/includes/file.php');
$upload_overrides = array('test_form' => false);
add_filter('upload_dir', 'cv_uploads_dir');
$movefile = wp_handle_upload($uploadedfile, $upload_overrides);
remove_filter('upload_dir', 'cv_uploads_dir');
if ($movefile) {
return basename($movefile['file']); //$uploadedfile['name'];
} else {
return "";
}
}
path set
function cv_uploads_dir($param)
{
$param['subdir'] = '/cvs';
$param['path'] = $param['basedir'] . $param['subdir'];
$param['url'] = $param['baseurl'] . $param['subdir'];
return $param;
}
now i want to send this in email using the wp_mail function. all other data is sent successfully but i dont know how to deal with the cv.
Mail function
function SendCareers_Email($pst)
{
$to = get_option('career_email');
$from = $pst['e-mail'];
$name = $pst['firstname'];
$cvname="/uploads/cvs/".$sqldata['att_ment'];
$subject = "Applying for the job " . $pst['title'];
$message= "Candidate Name:-" . $name . "<br/>";
$message .= "Job Title Applied:-" . $pst['title'] . "<br/>";
if(!empty($pst['country'])){
$message .= "Country Of Resindency:-" . $pst['country'] . "<br/>";
}
if(!empty($pst['nationlaity'])){
$message .= "Nationlaity:-" . $pst['nationlaity'] . "<br/>";
}
$attachments = array( WP_CONTENT_DIR . $cvname );
if(!empty($pst['mobileno'])){
$message .= "Phone Number:-" . $pst['mobileno'] . "<br/>";
}
add_filter('wp_mail_content_type', 'set_career_html_content_type');
$admin_headers = 'From: '.$name.' <'.$from .'>' . "\r\n\\";
wp_mail($to, $subject,$message , $admin_headers,$attachments);
remove_filter('wp_mail_content_type', 'set_career_html_content_type');
}
function set_career_html_content_type()
{
return 'text/html';
}
In your SendCareersEmail function change this part
$cvname="/uploads/cvs/".$_FILES['filecv']['name'];
$attachments = array(
$cvname
);
When inside a function only global variables or variables you pass into the function (in your case $pst) are available. So either pass in $sqldata to the function SendCVEmail($pst, $sqldata) or use the global call of $_FILES['filecv']['name']
I'm getting this error when trying to post from an AngularJS control to a PHP page to process. The object looks fine, but it keeps giving this error:
TypeError: Cannot read property 'protocol' of undefined
at urlIsSameOrigin (angular.js:17714)
at sendReq (angular.js:10225)
at serverRequest (angular.js:9944)
at processQueue (angular.js:14454)
at angular.js:14470
at Scope.$eval (angular.js:15719)
at Scope.$digest (angular.js:15530)
at Scope.$apply (angular.js:15824)
at HTMLFormElement.<anonymous> (jcs-auto-validate.min.js:6)
at HTMLFormElement.eventHandler (angular.js:3247)
Here is the code for the controller:
(function () {
angular
.module('contactApp')
.controller('FormCtrl', FormCtrl);
function FormCtrl ($http) {
/* jshint validthis: true */
var vm = this;
vm.formModel = {};
vm.success = false;
vm.error = false;
vm.onSubmit = function () {
console.log("I'm submitted");
console.log(vm.formModel);
$http({
method : 'POST',
URL : '/formProcess.php',
data : {
'name':vm.formModel.name,
'phoneNumber':vm.formModel.phoneNumber,
'email':vm.formModel.email,
'streetAddress':vm.formModel.streetAddress,
'cityStateZip':vm.formModel.cityStateZip,
'bedrooms':vm.formModel.bedrooms,
'bath':vm.formModel.baths,
'reason':vm.formModel.reason
},
headers : { 'Content-Type': 'application/x-www-form-urlencoded' }
})
.success(function(data, status, headers, config) {
vm.resultData = data;
alert("Message sent successfully. We'll get in touch with you soon.");
}).error(function(data, status, headers, config) {
vm.resultData = data;
alert("Sending message failed.");
});
/*.success( function(data, status, headers, config) {
if ( data.success ) {
vm.success = true;
console.log('happy');
} else {
vm.error = true;
console.log('sad');
}
});*/
}
}
FormCtrl.$inject = ['$http'];
})();
and for the PHP to send the email:
<?php
// ===========================================
// Define custom variables
// ===========================================
$emailTo = '---.com';
$nameTo = 'test';
$subject = 'test';
// ===========================================
// Validate and send email
// ===========================================
if($_SERVER['REQUEST_METHOD'] == 'POST') {
$response = array( 'success' => false );
$formData = file_get_contents( 'php://input' );
$data = json_decode( $formData );
/*if ( $data->submit ) {*/
$name = $data->name;
$phoneNumber = $data->phoneNumber;
$email = $data->email;
$streetAddress = $data->streetAddress;
$cityStateZip = $data->cityStateZip;
$bedrooms = $data->bedrooms;
$baths = $data->baths;
$reason = $data->reason;
//check if any of the inputs are empty
if ( $name != '' && $phoneNumber != '' && $email != '' && $streetAddress != '' && $cityStateZip != '' && $bedrooms != '' && $baths != '' && $reason != '' ) {
$body = 'From: ' . $name . '\n';
$body .= 'Email: ' . $email . '\n';
$body .= 'Phone Number: ' . $phoneNumber . '\n';
$body .= 'Street Address: ' . $streetAddress . '\n';
$body .= 'City, State and Zip: ' . $cityStateZip . '\n';
$body .= 'Number of Bedrooms: ' . $bedrooms . '\n';
$body .= 'Number of Baths: ' . $baths . '\n';
$body .= 'Reason for Selling:\n ' . $reason . '\n\n';
$headers = 'From: '. $nameTo.' <'.$emailTo.'>' . "\r\n" . 'Reply-To: ' . $email;
$success = mail($emailTo, $subject, $body, $headers);
if ( $success ) {
$response[ 'success' ] = true;
}
}
/*}*/
}
echo json_encode( $response );
?>
Any thoughts as to what I might be missing here?
Thanks!
I have this form where I wan't people to sign up for receiving free stuff campaign. The form works fine and its send the details to the requested eMail.
Now this form should also write the details to a csv file that we can handle the data more easily.
I use this form:
$value) {
${"".$key} = $value;
}
if (!isset($email)) {
header( "Location: $formurl" );
exit;
}
if ($_POST['services']) {
foreach($_POST['services'] as $value) {
$check_msg .= "- $value\n";
}
}
function is_email($email) {
return ereg("^[^# ]+#[^#]+\.[^# ]+$", $email);
}
function validate_email($email) {
// Create the syntactical validation regular expression
$regexp = "^([_a-z0-9-]+)(\.[_a-z0-9-]+)*#([a-z0-9-]+)(\.[a-z0-9-]+)*(\.[a-z]{2,4})$";
// Presume that the email is invalid
$valid = 0;
// Validate the syntax
if (eregi($regexp, $email))
{
list($username,$domaintld) = split("#",$email);
// Validate the domain
if (getmxrr($domaintld,$mxrecords))
$valid = 1;
} else {
$valid = 0;
}
return $valid;
}
$formurl = "/sticker/index.php" ;
$errorurl1 = "/sticker/error.php" ;
$errorurl2 = "/sticker/error.php" ;
$thankyouurl = "/sticker/success.php#start" ;
$http_referrer = getenv( "HTTP_REFERER" );
// get POST && GET vars to run with 'register_globals off'
//foreach($_GET AS $key => $value) {
// ${"".$key} = $value;
//}
$messageproper =
"============================================================\n" .
"Sticker Request $firstname $lastname\n" .
"============================================================\n\n" .
"KUNDENDATEN\n\n" .
"Vorname: $firstname\n" .
"Nachname: $lastname\n" .
"Firma: $company\n" .
"Strasse: $street\n" .
"Strasse2: $street2\n" .
"PLZ: $zip\n" .
"City: $city\n" .
"Land: $country\n\n" .
"Telefon: $phone\n" .
"eMail: $email\n" .
"Facebook Name: $fbname\n\n" .
"--------------------------------------\n\n" .
"Bemerkung: $comment\n\n" .
"============================================================\n\n" ;
$myFile = "/sticker/sticker.txt";
$fh = fopen($myFile, 'a');
$stringData = "\r\n";
$x=0;
foreach($_POST AS $key => $value) {
$x!=0?$stringData=",".$stringData:'';
$stringData='"'.$firstname.'";"'.$lastname.'";"'.$company.'";"'.$street.'";"'.$street2.'";"'.$zip.'";"'.$city.'";"'.$country.'";"'.$phone.'";"'.$email.'";"'.$fbname.'";"'.$comment.'"'."\r\n";
$x++;
}
fwrite($fh, $stringData);
fclose($fh);
$mailto = 'email#domain.com' ;
$subject = "Free Sticker Campaign: $company - $firstname $lastname";
mail($mailto, $subject, $messageproper, "From: \"$firstname $lastname\" <$email>\nReply-To: \"$lastname\" <$email>\nX-Mailer: chfeedback.php 2.01" );
header( "Location: $thankyouurl" );
exit;
?>
As I said nothing gets written to the CSV File I declared in $myFile.
Would be great if someone could let me know what to do.
Thanks.
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.
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>