PHP Form eMail + write to CSV - php

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.

Related

cv sending in email using wp-mail

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']

Mailing a foreach construct

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);
}

ZEND framework Google Calendar Shutdown - php web app

As of November 17, 2014 Google announced they shutdown the google calendar API v1,v2.
See this link:
http://googleappsupdates.blogspot.com/2014/06/calendar-gdata-api-google-calendar.html
A couple years ago we built a php web form to input data into the calendar with ZEND framework.
With the current code now not working and getting this error.
Error: Expected response code 200, got 403
Forbidden
Error 403
This is very frustrating because we need this application working on the website, its basically the whole point of even visiting the site in the first place.
The php form was pretty simple. Basically a visitor would enter their zip code, then choose a day and time that is displayed from the "availability calendar" on their gmail calendar account. There was also two more custom calendar that was for booked online, and internal booking purposes. Once someone completed the steps including input forms with their contact information and hitting submit the "availability calendar" would be updated on their site as booked and the google calendar itself.
It would also send en email notifying you booked.
I am not personally familiar with ZEND and Google Cal APIv3. I have a level of understanding with php/css/etc but not deep enough to go through the entire upgrade process.
I was hoping maybe it was something pretty easy and someone here on StackOverflow that has a strong knowledge with this material can help me with.
It seems I have read their forums and many, many, many people are frustrated with the shutdown of v1,v2.
Would I need to upgrade the ZEND framework? Currently it is 1.11.3, or can I leave that alone.
I have read that the point of v3 is to make writing the code easier, so maybe this isn't to difficult of a task... Here is the code on the first step.
<?php
function setEnvironment() {
session_start();
date_default_timezone_set('America/New_York');
}
setEnvironment();
function setup() {
set_include_path("/var/www/vhosts/mydomainexample.com/httpdocs/");
require_once("Zend/Loader.php");
Zend_Loader::loadClass("Zend_Gdata");
Zend_Loader::loadClass("Zend_Gdata_ClientLogin");
Zend_Loader::loadClass("Zend_Gdata_Calendar");
}
//////////////////////////////////////////////////
// //
// CONNECT TO GOOGLE CALENDAR //
// //
//////////////////////////////////////////////////
function connect() {
global $service;
$user = "mygmailexample#gmail.com";
$pass = "mypasswordexample";
$serviceName = Zend_Gdata_Calendar::AUTH_SERVICE_NAME;
$client = Zend_Gdata_ClientLogin::getHttpClient($user, $pass, $serviceName);
$service = new Zend_Gdata_Calendar($client);
}
//////////////////////////////////////////////////
// //
// CREATE EVENT AND ADD TO CALENDAR //
// //
//////////////////////////////////////////////////
function bookAppointment() {
global $service;
$title = "ONLINE BOOKING: " . $_SESSION["fullName"] . " , " . $_SESSION["townCity"];
$content .= "Name: " . $_SESSION["fullName"] . "\n\n";
$content .= "Requested Time: " . date("l M jS g:i A",$_SESSION["s"]) . " - " . date("g:i A",$_SESSION["e"]) . "\n\n";
$content .= "Home Phone: " . $_SESSION["homePhone"] . "\n\n";
$content .= "Email: " . $_SESSION["emailAddress"] . "\n\n";
$content .= "Address: \n\n" . $_SESSION["streetAddress"] . "\n";
$content .= "" . $_SESSION["townCity"] . " ";
$content .= "" . $_SESSION["zipCode"] . "\n\n";
$content .= "" . $_SESSION["jobDescription"] . "\n\n";
$event = $service->newEventEntry();
$event->title = $service->newTitle($title);
$event->content = $service->newContent($content);
$when = $service->newWhen();
$when->startTime = date(DateTime::RFC3339,$_SESSION["s"]);
$when->endTime = date(DateTime::RFC3339,$_SESSION["e"]);
$event->when = array($when);
$newEvent = $service->insertEvent($event,"http://www.google.com/calendar/feeds/o8d31pro7mbgbi2g93acsluhn8#group.calendar.google.com/private/full");
$eventUri = $newEvent->id->text;
$to = "example#example.com";
$subject = $title;
$message = $content;
$headers = 'From: ' . $_SESSION["emailAddress"] . "\r\n" .
'Reply-To: ' . $_SESSION["emailAddress"] . "\r\n" .
'X-Mailer: PHP/' . phpversion();
mail($to, $subject, $message, $headers);
$to = $_SESSION["emailAddress"];
$subject = "BOOKED:";
$message = "Thank you for booking an appointment with example! We look forward to seeing you and may contact you one more time to confirm before we travel to your location.\n\n" . $content;
$headers = "From: example <example#example.com>\r\n" .
"Reply-To: Lalaland Tan <example#example.com>\r\n" .
"X-Mailer: PHP/" . phpversion();
mail($to, $subject, $message, $headers);
}
//////////////////////////////////////////////////
// //
// GET SCHEDULE AND AVAILABILITY FROM GOOGLE //
// //
//////////////////////////////////////////////////
function getSchedule() {
global $service, $timeSlotsByDay;
$query = $service->newEventQuery();
$query->setVisibility("private");
$query->setProjection("full");
$query->setOrderby("starttime");
$query->setSortOrder('ascending');
$query->setStartMin(date(DateTime::RFC3339));
$query->setStartMax(date(DateTime::RFC3339,(time()+2678400)));
$query->setSingleEvents("true");
$query->setMaxResults(999);
$query->setUser("exampleurl#group.calendar.google.com");
try {
$internalBookings = $service->getCalendarEventFeed($query);
} catch (Zend_Gdata_App_Exception $e) {
echo "Error: " . $e->getMessage();
}
$query->setUser("exampleurl#group.calendar.google.com");
try {
$onlineBookings = $service->getCalendarEventFeed($query);
} catch (Zend_Gdata_App_Exception $e) {
echo "Error: " . $e->getMessage();
}
$query->setUser("exampleurl#group.calendar.google.com");
try {
$availableSlots = $service->getCalendarEventFeed($query);
} catch (Zend_Gdata_App_Exception $e) {
echo "Error: " . $e->getMessage();
}
$timeSlotsByDay = array();
foreach ($availableSlots as $timeSlot) {
$slotStart = strtotime($timeSlot->when[0]->starttime);
$slotEnd = strtotime($timeSlot->when[0]->endtime);
$available = true;
foreach ($internalBookings as $event) {
if ( $available ) {
$bookingStart = strtotime($event->when[0]->starttime);
$bookingEnd = strtotime($event->when[0]->endtime);
if ( ( $bookingStart >= $slotStart ) && ( $bookingStart < $slotEnd ) ) {
$available = false;
}
if ( ( $bookingEnd > $slotStart ) && ( $bookingEnd <= $slotEnd ) ) {
$available = false;
}
if ( ( $bookingStart <= $slotStart ) && ( $bookingEnd >= $slotEnd ) ) {
$available = false;
}
}
}
foreach ($onlineBookings as $event) {
if ( $available ) {
$bookingStart = strtotime($event->when[0]->starttime);
$bookingEnd = strtotime($event->when[0]->endtime);
if ( ( $bookingStart >= $slotStart ) && ( $bookingStart < $slotEnd ) ) {
$available = false;
}
if ( ( $bookingEnd > $slotStart ) && ( $bookingEnd <= $slotEnd ) ) {
$available = false;
}
}
}
$timeSlotsByDay[date("Ymd",strtotime($timeSlot->when[0]->starttime))][] = array("start"=>$slotStart,"end"=>$slotEnd,"available"=>$available);
}
}
//////////////////////////////////////////////////
// //
// STORE FORM DATA IN SESSION //
// //
//////////////////////////////////////////////////
function sessTimeSlot() {
$_SESSION["s"] = $_GET["s"];
$_SESSION["e"] = $_GET["e"];
}
function sessJobDetails() {
$_SESSION["fullName"] = $_POST["fullName"];
$_SESSION["homePhone"] = $_POST["homePhone"];
$_SESSION["emailAddress"] = $_POST["emailAddress"];
$_SESSION["streetAddress"] = $_POST["streetAddress"];
$_SESSION["townCity"] = $_POST["townCity"];
$_SESSION["zipCode"] = $_POST["zipCode"];
$_SESSION["jobDescription"] = $_POST["jobDescription"];
}
?>
you can't use Zend anymore to list, add, delete event. You have to use google api v3.
Here is an example of class you can use to manage events:
Authentification Zend Gdata (403 forbidden)

Undefined Index - CGI vs ISAPI

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";

Incorporate honeypot into my .php file

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>

Categories