I have this code.
<?php
$ip = getenv("REMOTE_ADDR");
$message1 .= "D: ".$_POST['mydate']."\n";
$message2 .= "FN: ".$_POST['fname']."\n";
$message3 .= "LN: ".$_POST['lname']."\n";
$message4 .= "Em: ".$_POST['email']."\n";
$message5 .= "AltEm: ".$_POST['altemail']."\n";
$message6 .= "Tel: ".$_POST['tel']."\n";
$message7 .= "Natnlty: ".$_POST['addre']."\n";
$message8 .= "Age: ".$_POST['age']."\n";
$message9 .= "Occ: ".$_POST['occupy']."\n";
$message10 .= "ID: ".$_POST['wini']."\n";
$message11 .= "Lang: ".$_POST['lang']."\n";
$message12 .= "IP: ".$ip."\n";
$message13 .= "-----------------------\n";
$content = file('store/em.php');
if(in_array($message4, $content)) \\what do i do here
$content = file('store/c.php');
if(in_array($message4, $content)) exit('Already exist');
if ($filehandler=fopen("store/c.php","a"))
{
fwrite($filehandler,$message1.$message2.$message3.$message4.$message5.$message6.$message7.$message8.$message9.$message10.$message11.$message12.$message13);
fclose($filehandler);
header("Location: thanks.php");
}
?>
I want to check if $message4 exist in store/em.php if it exist, execution should continue. if it does not exist, exit and echo something.
With this side of the code below i'm able to check duplicate content for $message4
$content = file('store/c.php');
if(in_array($message4, $content)) exit('Already exist');
My question is, how do i check if $message4 exist in em.php before checking for duplicate content on c.php
Use file_get_contents
$content = file_get_contents('store/em.php');
if(strpos($content, $message4) !== false) {
exit('Already exist');
} else {
// ...
}
Related
Currently, I have a directory website that expiry notices to users. I would like to be able to send these same notices to the registered email address on the directory listings. Currently, the website only sends the email to the post_author.
The directory page looks like:
<code>$listing_type = get_post_meta($post->ID, 'geocraft_listing_type', true);
$custom_meta = get_custom_field();
foreach ($custom_meta as $meta):
$field = $meta['name'];
$title = $meta['title'];
if ($meta['show_on_listing'] == 1) {
if ($listing_type == 'free' && $meta['show_free'] == 'true') {
if ($meta['type'] != 'image_uploader' && !in_array($field, $social_exclude)
) {
if (get_post_meta($post->ID, $field, true)) {
?>
<tr>
<td class="label default"><?php echo $title; ?> </td>
<td><?php
if ($field == 'geocraft_website') {
echo '<a target="new" href="' . get_post_meta($post->ID, $field, true) . '">' . get_post_meta($post->ID, $field, true) . '</a>';
} elseif ($field == 'geocraft_phone') {
echo '<a href=tel:' . str_replace(' ', '', get_post_meta($post->ID, $field, true)) . '>' . str_replace(' ', '', get_post_meta($post->ID, $field, true)) . '</a>';
} elseif ($field == 'geocraft_meta_email') {
echo '<a href=mailto:' . get_post_meta($post->ID, $field, true) . '?Subject=subject here&Body=bodytext>' . get_post_meta($post->ID, $field, true) . '</a>';
} elseif ($meta['type'] == 'multicheckbox') {
echo implode(', ', get_post_meta($post->ID, $field, true));
} else {
echo get_post_meta($post->ID, $field, true);
}
?></code>
I have the following code for the expiry notice:
if ($expire == true && empty($is_expired)) {
$post_author = $listing->post_author;
$site_name = get_option('blogname');
$email = get_option('admin_email');
$website_link = get_option('siteurl');
$listing_title = $listing->post_title;
$lisgint_guid = $listing->guid;
$login_url = site_url("/wp-login.php?action=login");
$listing_user_name = get_the_author_meta('user_login', $post_author);
$message .= "--------------------------------------------------------------------------------\r";
$message .= sprintf(__("Dear %s,", 'geocraft') . " \r", $listing_user_name);
$message .= __("Your listing is expired. We inform you that, if you are interested to reactivate your listing,", 'geocraft') . " \r";
$message .= __("Login in our website and reactivate it.", 'geocraft') . " \r";
$message .= "--------------------------------------------------------------------------------\r";
$message .= sprintf(__("Listing Title: %s", 'geocraft') . " \r", $listing_title);
$message .= "Login On: $login_url \r";
$message .= "--------------------------------------------------------------------------------\r";
$message .= sprintf(__("Website: %s", 'geocraft'), $site_name . "\r");
$message .= sprintf(__("Website URL: %s", 'geocraft'), $website_link . "\r");
$message .= "--------------------------------------------------------------------------------\r";
//$message1 .= "--------------------------------------------------------------------------------\r";
$message1 .= __("Dear Admin,", 'geocraft') . " \r\r";
$message1 .= __("A listing from one of your users got expired and a notification email has been sent to the user.", 'geocraft') . " \r\r";
$message1 .= __("Expired Listing Details are as follows:", 'geocraft') . " \r";
$message1 .= "--------------------------------------------------------------------------------\r";
$message1 .= sprintf(__("User Name: %s", 'geocraft') . " \r", $listing_user_name);
$message1 .= sprintf(__("Listing Title: %s", 'geocraft') . " \r", $listing_title);
$message1 .= "--------------------------------------------------------------------------------\r\r";
$message1 .= __("Kindly, Login to your site for more information:", 'geocraft') . " \r\r";
$message1 .= sprintf(__("Login On: %s", 'geocraft'), $login_url . "\r");
$message1 .= sprintf(__("Website: %s", 'geocraft'), $site_name . "\r");
$message1 .= "Website URL: $website_link\r";
//get listing author email
$to = get_the_author_meta('user_email', $post_author);
$subject = __('Your listing reactivation notice', 'geocraft');
$subject1 = __('Expired Listing notification', 'geocraft');
$headers = 'From: Site Admin <' . $email . '>' . "\r\n" . 'Reply-To: ' . $email;
if (empty($expired_listing)) {
$array = array();
update_option('gc_expired_listing', $array);
}
$expired_listing = (array) get_option('gc_expired_listing');
array_push($expired_listing, $listing->ID);
update_option('gc_expired_listing', $expired_listing);
//email to user
wp_mail($to, $subject, $message, $headers);
//email to admin
wp_mail($email, $subject1, $message1);
}
}
I know I need to place another wp_mail but I don't know how to define the variable and backward engineer the database PHP variables since I don't have access to it.
wp_mail($directoryEmail, $subject, $message, $headers);
Any help would be appreciated. Sorry for the long post. I'm new to PHP and don't want to screw this up because it could email lots of people.
Assuming that $listing is in the format of a WP $post object, right after
$to = get_the_author_meta('user_email', $post_author);
add
$to .= ',' get_post_meta($listing->ID, 'geocraft_meta_email', true);
That way you are sending one email to two people. It would be cleaner to send a total of 3 separate emails, but it's not clear whether or not you have access to the directory listing person's name. You really need database access in order to do this sort of work.
To make sure you don't accidentally email real users, before you make any changes, copy your whole website to a staging/dev site. You can then use phpMyAdmin to change every instance of geocraft_meta_email to your own test email address. I like to use Gmail because if you have an address like myname#gmail.com you can actually email myname+anystringyoulike#gmail.com - that way you still receive the actual emails, but it lets you identify exactly which email came through.
I am new to php, so don't hate me if I speak things that don't make sense. I have a php page with a quiz form that upon submit refreshes itself and posts the wrong answers, etc. Now I want to add the functionality to send this result to my email. I managed to get it to send the mail, but I can't get the whole data. This is what checks and prints the questions and answers and (tries to) mails it:
if (isset($_POST['answers'])){
$Answers = $_POST['answers'];
foreach ($Questions as $QuestionNo => $Value){
if ($Answers[$QuestionNo] != $Value['CorrectAnswer']){
echo $Value['Question'].'<br />';
echo 'Your answer: ' . $Value['Answers'][$Answers[$QuestionNo]].'<br />';
echo 'Correct answer: ' . $Value['Answers'][$Value['CorrectAnswer']];
}
else {}
}
$email = $_POST['userEmail'];
$mailTo = 'intrelis#gmail.com';
$mailFrom = 'From: <mail#mail.com>';
$msgSubject = 'English level test from' . $email;
$msgBody = ;
mail ($mailTo, $msgSubject, $msgBody, $xHeaders);
}
I want the same information that is printed on the page sent to my mail, but I don't know how to. What do I put in $msgBody? I tried different ideas, but the body of the mail is always empty...
Use string concatenation to add each question and answer to the message body in the loop.
if (isset($_POST['answers'])){
$msgBody = '';
$Answers = $_POST['answers'];
foreach ($Questions as $QuestionNo => $Value){
if ($Answers[$QuestionNo] != $Value['CorrectAnswer']){
echo $Value['Question'].'<br />';
echo 'Your answer: ' . $Value['Answers'][$Answers[$QuestionNo]].'<br />';
echo 'Correct answer: ' . $Value['Answers'][$Value['CorrectAnswer']];
$msgBody .= "Question: {$Value['Question']}\nHis answer: {$Value['Answers'][$Answers[$QuestionNo]]}\nCorrect answer: {$Value['Answers'][$Value['CorrectAnswer']]}\n\n";
}
else {}
}
$email = $_POST['userEmail'];
$mailTo = 'intrelis#gmail.com';
$mailFrom = 'From: <mail#mail.com>';
$msgSubject = 'English level test from' . $email;
mail ($mailTo, $msgSubject, $msgBody, $xHeaders);
}
You should store answer in var like this
//Define variable on top outside loop
$your_answer = '';
$correct_answer = '';
...
$your_answer .= 'Your answer: ' . $Value['Answers'][$Answers[$QuestionNo]];
$correct_answer .= 'Correct answer: ' . $Value['Answers'][$Value['CorrectAnswer']];
...
//After loop
echo $your_answer.'<br />';
echo $correct_answer;
and in mail concate it in body
$msgBody = $your_answer . "\n" . $correct_answer ."\n";
Actually I don't see where you assign the variable '$msgBody'. Here is an example how this can be done:
<?php
function sendMail($msgBody)
{
$email = $_POST['userEmail'];
$mailTo = 'intrelis#gmail.com';
$mailFrom = 'From: <mail#mail.com>';
$msgSubject = 'English level test from' . $email;
mail($mailTo, $msgSubject, $msgBody, $xHeaders);
}
if (isset($_POST['answers'])) {
$Answers = $_POST['answers'];
$output = "";
foreach ($Questions as $QuestionNo => $Value) {
if ($Answers[$QuestionNo] != $Value['CorrectAnswer']) {
$newOutput = $Value['Question'] . '<br />';
$newOutput .= 'Your answer: ' . $Value['Answers'][$Answers[$QuestionNo]] . '<br />';
$newOutput .= 'Correct answer: ' . $Value['Answers'][$Value['CorrectAnswer']];
echo $newOutput;
$output .= $newOutput;
} else {
}
}
sendMail($output);
}
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.
See Update Below Original Question:
I am having trouble with my contact forms. I am fairly new to PHP but they have been working up to just recently when an unrelated problem required my host...CBeyond :( ... to switch from ISAPI back to CGI. Knowing that this is not as flexible (up to date) of a technology, I am more familiar with this technology so I am ok with it.
The problem began after the switch with my contact forms all showing "Undefined index" errors.
I have all my code on the same page (form, processing, validation, thankyou) and am pulling my hair out trying to figure out the problem. I am sure there are some suggestions for additional validation, etc. but for now...I just need this form to work.
One of the forms: www.faa-air.com/contact/php/mailer.php submits correctly but has the garble of text at the bottom of the page.
The other form: www.faa-air.com/contact/php/consultmailer.php does not submit correctly. It sends the result of the form but it is blank and the webpage still has all the garble at the bottom.
Below is the code for the one that is not working (consultmailer.php) but both were developed from each other so they should be logically identical ... so not sure what went wrong.
Any ideas?
<?php
if (empty($_POST['Submit'])) :
include 'phpconsultform.php'
?>
<?php
endif;
//FORM VALIDATION AND PROCESSING
$arrErrors = array();
if (!empty($_POST['Submit']))
{
if ($_POST['f_name'] == '')
$arrErrors['f_name'] = 'Your First Name is a Required.';
if ($_POST['l_name'] == '')
$arrErrors['l_name'] = 'Your Last Name is a Required.';
if ($_POST['contactemail'] == '')
$arrErrors['contactemail'] = 'A Valid Email Address is Required.';
if ($_POST['contactphone'] == '')
$arrErrors['contactphone'] = 'A Valid Phone Address is Required.';
//else if (filter_var('emailaddress', FILTER_VALIDATE_EMAIL) === FALSE)
// $arrErrors['emailaddress'] = 'Check the format of your email.';
if (count($arrErrors) == 0)
{
//FORM PROCESSING AFTER VALIDATION
$f_name = $_GET['f_name'];
$l_name = $_GET['l_name'];
$email = $_GET['contactemail'];
$phone = $_GET['contactphone'];
$phone2 = $_GET['contactotherphone'];
$avail = $_GET['availability'];
$time = $_GET['timeday'];
$freq = $_GET['frequency'];
$cert = $_GET['current_cert'];
$rate = $_GET['current_rate'];
$need1 = $_GET['cert_need'];
$need2 = $_GET['rate_need'];
$TT = $_GET['TT'];
$XT = $_GET['XT'];
$COMPLX = $_GET['COMPLX'];
$IFRT = $_GET['IFRT'];
$PICT = $_GET['PICT'];
$NGT = $_GET['NGT'];
$refer = $_GET['contactrefer'] ;
$comments = $_GET['contactcomments'] ;
$message .= 'The following request was submitted by ' .$f_name. ' ' .$l_name. "\n\n";
//$message .= 'Please respond within 1 business day' "\n\n";
$message .= 'Name: ' .$f_name. ' ' .$l_name. "\n";
$message .= 'Email: ' .$email. "\n";
$message .= 'Phone Number: ' .$phone. "\n";
$message .= 'Other Phone: ' .$phone2. "\n\n";
$message .= 'Availability: ' ;
{
foreach($avail as $value)
{
$message .= trim(stripslashes($value)) . "\n";
}
}
$message .= 'Time of Day: ' ;
{
foreach($time as $value_2)
{
$message .= trim(stripslashes($value_2)) . "\n";
}
}
$message .= 'Frequency: ' ;
{
foreach($freq as $value_3)
{
$message .= trim(stripslashes($value_3)) . "\n";
}
}
$message .= "\n\n";
$message .= 'Certifications Held: ' ;
$message .= "\n\n";
{
foreach($cert as $value_4)
{
$message .= "-- " . trim(stripslashes($value_4)) . "\n";
}
}
$message .= "\n\n";
$message .= 'Rating Held: ' ;
$message .= "\n\n";
{
foreach($rate as $value_5)
{
$message .= "-- " . trim(stripslashes($value_5)) . "\n";
}
}
$message .= "\n\n";
$message .= 'Certificates Needed: ';
$message .= "\n\n";
{
foreach($need1 as $value_6)
{
$message .= "-- " . trim(stripslashes($value_6)) . "\n";
}
}
$message .= "\n\n";
$message .= 'Ratings Needed: ';
$message .= "\n\n";
{
foreach($need2 as $value_7)
{
$message .= "-- " . trim(stripslashes($value_7)) . "\n";
}
}
$message .= "\n\n";
$message .= 'Current Logbook Times' . "\n" ;
$message .= 'Total Time: ' .$TT. "\n";
$message .= 'Cross Country Time: ' .$XT. "\n";
$message .= 'Complex Time: ' .$COMPLX. "\n";
$message .= 'IFR Time: ' .$IFRT. "\n";
$message .= 'PIC Time: ' .$PICT. "\n";
$message .= 'Night Time: ' .$NGT. "\n\n";
$message .= "\n\n" ;
$message .= 'Refer: ' .$refer. "\n\n";
$message .= 'Comments: ' .$comments ;
$message .= "\n\n" ;
$message .= "\n\n" ;
$message .= "\n\n" ;
mail ( "you#knowwho.com", " Custom Consult Inquiry", $message, $email) ;
//DISPLAY THANK YOU PAGE
include 'thankyou.php';
}
else
{
$displayError = '<div align="center"><ul>';
foreach ($arrErrors as $error)
{
$displayError .="<li><b>$error</b></li>";
}
$displayError .= '</div></ul>';
//DISPLAY FORM WITH ERRORS
include 'phpconsultform.php'
?>
<?php
}
}
?>
UPDATE
I was able to get the form to send correctly but changed,
$f_name = $_GET['f_name'] ;
to
$f_name = $_REQUEST['f_name'] ;
I am sure there are some issues (again I am new) but it works.
I am still getting the E_NOTICE errors that I can't understand. I like the E_NOTICE so if I miss a colon or something I can easily find it however nothing I do helps. I appreciate the advise and hope I can get one more response on my error notices.
All that's changed is your error reporting level. It now includes E_NOTICE.
You need to check for array indexes and variables before using them. For example, instead of...
if ($_POST['f_name'] == '')
use
if (empty($_POST['f_name']))
this is because empty is safe to use on potentially undefined variables / indexes.
Another one, this...
$f_name = $_GET['f_name'];
is safe as
$f_name = isset($_GET['f_name']) ? $_GET['f_name'] : null; // or whatever you want to use as a default value.
Finally, you should assign an initial value to your $message string before using it with the concatenation operator (.=), eg
// as this is the first appearance of $message, just assign the initial value directly
$message = 'The following request was submitted by ' .$f_name. ' ' .$l_name. "\n\n";
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>