Sending email in contact page not working - email

I am using following code, copied from a website, for a contact page. But I am not getting any emails and the attached files don't find their way to my webserver folder /var/www/. Am I missing something here?
I am running this code on localhost.
email.php
ob_start();
$to = 'baltusaj#gmail.com';
/*$name = $_POST['name'];
$email = $_POST['email'];
$confirm_email = $_POST['confirm_email'];
$subject = $_POST['subject'];
$comments = $_POST['comments'];
$hidden = $_POST['hidden'];
$from = $email;
*/
$keys = array('name', 'email', 'confirm_email', 'subject', 'comments', 'hidden');
foreach($keys as $key)
{
$$key = isset($_POST[$key]) ? $_POST[$key] : null ;
}
print ('
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
<title>Email</title>
<script type="text/javascript">
/*<![CDATA[*/
function progress(){
intWidth = parseInt(document.getElementById("container1").style.width) + 1;
if(intWidth <= 400){
document.getElementById("container1").style.width = intWidth+"px";
}else{
document.getElementById("container1").style.width = 0;
}
setTimeout("progress()",300);
}
/*]]>*/
</script>
</head>
<body>
');
//Make sure email and confirm email are the same
if (!empty ($hidden)) {
if ($email == $confirm_email) {
}else{
$email = '';
$confirm_email = '';
}
}
//Do a reg_ex check on the email
if (!empty ($hidden)) {
$regexp = "^([_a-z0-9-]+)(\.[_a-z0-9-]+)*#([a-z0-9-]+)(\.[a-z0-9-]+)*(\.[a-z]{2,4})$";
if (eregi($regexp, $email))
{
}else{
$email = '';
$confirm_email = '';
}
}
// End of email checking
if (empty ($hidden)) {
print ('<div id="container2">
<h1 id="content_h1"><a name="text"> E-mail </a></h1> <p>Please use the following form to e-mail us:</p>
');
include ("form.php");
print ('</div>
<div id="container0" style="display: none;">
<p style="font-size: 15pt; font-family: sans-serif; color:#fd6700; background:#fff;">
Loading...
</p>
<div id="container1" style="width:0px; height:5px; background-color:#fd6700; margin-top:0px; text-align: left;"></div>
<p>Please be patient while your data is processed. This may take a few moments especially if you are uploading a file.</p>
</div>
');
}
if (!empty ($hidden)) {
if ($_FILES['fileatt']['error'] == 1){
print ('<h1 id="content_h1"><a name="text">There has been an error</a></h1>
<p>The maximum file size that can be uploaded using this form is 2 megabytes.
</p>');
}elseif ( (!empty ($name)) && (!empty ($email)) && (!empty ($comments))&& (!empty ($subject))) {
// Get html message content
$form_data = "<p>This email is from <span class=\"bold\">$name</span> \n\n ";
$form_data .= "<p>$comments</p>";
$message = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \n" .
" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\"> \n" .
"<html xmlns=\"http://www.w3.org/1999/xhtml\"> \n" .
"<head> \n" .
" <meta http-equiv=\"content-type\" content= \n" .
" \"text/html; charset=iso-8859-1\" /> \n" .
"<style type=\"text/css\"> \n" .
"body { font-size: 9pt; font-family: verdana, sans-serif; color: #000; background:#fff; } \n" .
".bold { font-weight: bold; } \n" .
"</style> \n" .
"</head> \n" .
"<body>$form_data \n" .
"</body> \n" .
"</html> \n\n";
// Obtain file upload vars
$fileatt = $_FILES['fileatt']['tmp_name'];
$fileatt_type = $_FILES['fileatt']['type'];
$fileatt_name = $_FILES['fileatt']['name'];
$headers = "From: $from";
if (is_uploaded_file($fileatt)) {
// Read the file to be attached ('rb' = read binary)
$file = fopen($fileatt,'rb');
$data = fread($file,filesize($fileatt));
fclose($file);
// Generate a boundary string
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
// Add the headers for a file attachment
$headers .= "\nMIME-Version: 1.0\n" .
"Content-Type: multipart/mixed;\n" .
" boundary=\"{$mime_boundary}\"";
// Add a multipart boundary above the html message
$message = "This is a multi-part message in MIME format.\n\n" .
"--{$mime_boundary}\n" .
"Content-Type: text/html; charset=\"iso-8859-1\"\n" .
"Content-Transfer-Encoding: 7bit\n\n" .
$message . "\n\n";
// Base64 encode the file data
$data = chunk_split(base64_encode($data));
//We now have everything we need to write the portion of the message that contains the file attachment. Here's the code:
// Add file attachment to the message
$message .= "--{$mime_boundary}\n" .
"Content-Type: {$fileatt_type};\n" .
" name=\"{$fileatt_name}\"\n" .
"Content-Disposition: attachment;\n" .
" filename=\"{$fileatt_name}\"\n" .
"Content-Transfer-Encoding: base64\n\n" .
$data . "\n\n" .
"--{$mime_boundary}--\n";
}else{
// Generate a boundary string
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
// Add the headers for a file attachment
$headers .= "\nMIME-Version: 1.0\n" .
"Content-Type: multipart/mixed;\n" .
" boundary=\"{$mime_boundary}\"";
// Add a multipart boundary above the html message
$message = "This is a multi-part message in MIME format.\n\n" .
"--{$mime_boundary}\n" .
"Content-Type: text/html; charset=\"iso-8859-1\"\n" .
"Content-Transfer-Encoding: 7bit\n\n" .
$message . "\n\n";
}
//That completes the modifications necessary to accommodate a file attachment. We can now send the message with a quick call to mail:
// Send the message
mail($to, $subject, $message, $headers);
$body = "Dear $name, \n\nThank you for your email. We will contact you as soon as possible regarding the matter. \n \n";
mail ($email, "Re: $subject", $body, 'From:you#your_email.com');
print ('<h1 id="content_h1"><a name="text"> Thank you </a></h1> <p>We will contact you as soon as possible. You will receive an automatic e-mail immediately confirming the reception of your email.</p>');
}else{
print ('<h1 id="content_h1"><a name="text">There has been an error</a></h1> <p>Please fill in all the compulsory fields correctly and then resubmit the form. Thank you.</p>');
include ("form.php");
}
}
// This is the end of the insert
print ('
</div>
</body>
</html>
');
ob_end_flush();
?>
form.php
<div id="form">
<form action="email.php" enctype="multipart/form-data" method="post" onsubmit="
document.getElementById('container0').style.display='';
document.getElementById('container2').style.display='none';
progress();
return true;">
<fieldset id="fieldset">
<label for="name">Contact name<span style="color: red;">*</span>:</label>
<input <?php if (!empty ($hidden)) { if (empty ($name)) { print 'style="background: pink;"'; } } ?> class="form_elements" id="name" type="text" name="name" value="<?php print "$name"; ?>" tabindex="1" />
<br />
<label for="email">E-mail address<span style="color: red;">*</span>:</label>
<input <?php if (!empty ($hidden)) { if (empty ($email)) { print 'style="background: pink;"'; } } ?> class="form_elements" id="email" type="text" name="email" value="<?php print "$email"; ?>" tabindex="1" />
<br />
<label for="confirm_email">Confirm e-mail<span style="color: red;">*</span>:</label>
<input <?php if (!empty ($hidden)) { if (empty ($confirm_email)) { print 'style="background: pink;"'; } } ?> class="form_elements" id="confirm_email" type="text" name="confirm_email" value="<?php print "$confirm_email"; ?>" tabindex="1" />
<br />
<label for="subject">Subject<span style="color: red;">*</span>:</label>
<input <?php if (!empty ($hidden)) { if (empty ($subject)) { print 'style="background: pink;"'; } } ?> class="form_elements" id="subject" type="text" name="subject" value="<?php print "$subject"; ?>" tabindex="1" />
<br />
<label for="comments">Comments<span style="color: red;">*</span>:</label>
<textarea <?php if (!empty ($hidden)) { if (empty ($comments)) { print 'style="background: pink;"'; } } ?>class="form_elements" id="comments" name="comments" cols="19" rows="5" tabindex="1"><?php print "$comments"; ?></textarea>
<br /><br />
<label for="fileatt">Attach document:</label>
<input id="fileatt" type="file" name="fileatt" tabindex="1" />
<br />
<input type="hidden" name="hidden" value="1" /><br />
<label for="submit"><span style="color: red;">*</span> Compulsory fields.</label>
<input id="submit" type="submit" value="Send" tabindex="1" />
</fieldset>
</form>
</div>

For the kajillionth time on this site: Don't build your own mime messages, it's unreliable and painful. Use Swiftmailer or PHPMailer instead. PHP's mail() function is highly unreliable and cannot produce ANY useful diagnostics as to why things are failing. Swift/PHPMailer will both tell you exactly why something blew up.
beyond that, nowhere do you seem to be doing a move_uploaded_file(), so your uploaded files will be auto-deleted by PHP when the script exits. You MUST deal with the files yourself, which means you have to write code to move the files to whatever place you want them stored in.

Are you running an SMTP server on your localhost?

Related

How can we send the table data to mail using php?

i am displaying the daily report submitted by the user now i want to mail the same to email when the send email button is clicked. how can i do that in PHP ?
i used the following code
extract($_REQUEST);
if(isset($send_mail)){
$edata= $_POST['send_msg'];
echo "<script type='text/javascript'>alert('$edata');</script>";
$ka_semail=$_SESSION['user_email'];
$subject = "Report";
$body = $edata;
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= 'From: Info <'.$ka_semail.'>' . "\r\n";
$mchk= mail($ka_semail, $subject, $body, $headers);
if(isset($mchk)){
echo "<script type='text/javascript'>alert('Your data Sent sucessfully');</script>";
header("location:reports.php");
}
}
?>
<body>
<div id="main">
<header>
<div id="logo">
<div id="logo_text">
<a href="index.html">
<div style="background:#2A0000"><img src="images/kreamsoftlogo.png"/></a></div>
</div>
</div>
<?php include'nav.php'; ?>
</header>
<div id="site_content">
<div id="email-data">
<div id="content">
<div class="content" style="min-height:385px; width: 100%" >
<h1>Daily Report </h1>
<?
$current_date = date("d/m/Y");
$current_user = $_SESSION['user_login'];
$find = mysql_query("select * from k_dailyreport where kr_user='$current_user' AND kr_date='$current_date'");
?>
<div class="content_item">
<ul>
<?php
$numrow=mysql_num_rows($find);
if($numrow>0){
$sino = 0;
echo "<table border='0' width='100%'>";
echo "<tr class='head'>";
echo "<th>S.No</th>";
echo "<th>Project</th>";
echo "<th>Process</th>";
echo "<th>Process Date</th>";
echo "<th>Current Duration</th>";
echo "</tr>";
$sno=0;
while($row = mysql_fetch_array($find)){
$sno=$sno +1;
$sino++;
$cls = ($sino%2==0) ? "even" : "odd";
echo "<tr class='t1'>";
echo "<td>$sno</td>";
echo "<td>".$row['kr_project']."</td>";
echo "<td>".$row['kr_process']."</td>";
echo "<td>".$row['kr_rtime']."</td>";
echo "<td>".$row['kr_ctime']."</td>";
}?></td>
<?php
echo "</tr>";
?><form name="test" method="post"enctype="multipart/form-data" action="<?php echo $_SERVER['PHP_SELF'];?>">
<p style='padding-top: 15px;margin-right: 50px; float:right'><input class='submit' id="sendEmail" type="submit" name='sendmail' value='Send Mail' />
<input type="hidden" name="send_mail" value="send_mail" />
<input type="hidden" name="send_msg" value="<?php
$numrow=mysql_num_rows($find);
if($numrow>0){
$sino = 0;
echo "<table border='0' width='100%'>";
echo "<tr class='head'>";
echo "<th>S.No</th>";
echo "<th>Project</th>";
echo "<th>Process</th>";
echo "<th>Process Date</th>";
echo "<th>Current Duration</th>";
echo "</tr>";
$sno=0;
while($row = mysql_fetch_array($find)){
$sno=$sno +1;
$sino++;
$cls = ($sino%2==0) ? "even" : "odd";
echo "<tr class='t1'>";
echo "<td>$sno</td>";
echo "<td>".$row[1]."</td>";
echo "<td>".$row[2]."</td>";
echo "<td>".$row[3]."</td>";
echo "<td>".$row[3]."</td>";
echo "</tr>";
}echo "</table>";}?>" /></p>
</form>
<?
}else{
?>
<center><img style="text-align:center" src="images/no_record.gif" /></center>
<?
}
echo "</table>";
?>
</li>
</ul>
</div>
</div> </div>
</div>
</div>
i want to mail the entire table with data
Without knowing anything about your code, I can perhaps at least guess as to the structure of what builds this table. Maybe something along the lines of this?:
writeTableHeader();
foreach ($values as $value) {
writeTableRow($value);
}
writeTableFooter();
Maybe even abstracted into its own higher-level function?:
function writeTable($values) {
$result = '';
$result .= buildTableHeader();
foreach ($values as $value) {
$result .= buildTableRow($value);
}
$result .= buildTableFooter();
return $result;
}
Any such function or abstraction can be used to construct the HTML for the email body as well...
// ... previously building the overall email body
$mailBody .= writeTable($values);
// ... maybe some more email body elements as well
mail($to, $subject, $mailBody);
Styling the email will be another story, of course. It's best not to rely on linked resources in an HTML email, those tend not to be requested by mail clients as they're often abused by spammers and the like. You can perhaps include the style sheet(s) as an "embedded resource" in the email, though in most cases I think inline styling is probably best for emails. (Some mail clients might not even load an embedded resource, at least not without first prompting the user, which isn't an ideal user experience.)
Assuming you don't want to duplicate much code, the above method can be abstracted using the Form Template Method refactoring pattern (example here, among others).
I guess the point I'm getting at is that the email doesn't send the web page, but rather the web page and the email are both independent "views" of the underlying data. Common code between them can be abstracted and shared of course, but trying to re-use a webpage itself in an email is over-complicating the situation.

PHP form submits regardless of required/error handling attempts

newbie here
I am currently attempting to build a simple contact form to learn how best to build one. I've tried to make several fields required (name, email, do you like spam radio button). The required html5 element isn't working for me or I am not implementing it correctly based on what i've read here, on google and other places. Likewise the error/require messages don't display if someone attempts to submit a message. Instead the form goes through on submit even if NO content anywhere has been entered. I built this yesterday and have been working on the errors for about 24 hours now and am hoping to find some help here.
I currently am returning no errors, the form sends all information entered as hoped, but it also sends if NO information is entered and that doesn't seem like the best possible form to me. I've tried to build a function to help the required, but that doesn't seem to be working either.
Again, i'm new so if my mistakes are obvious and silly, please help em to understand them, that would be greatly appreciated.
current example can be found here
My code:
<!-- For PoohPot -->
<style TYPE="text/css">
input[type="text"]#website { display: none; }
input#website { display: none; }
.vSmall {font-size: 50%; text-align: center;}
</style>
<script>
$('form').submit(function(){
if ($('input#website').val().length != 0) {
return false;
}
});
</script>
<?php
//template.php
include '_inc/config.php';//holds arrays, et al.
include '_inc/functions.php';//holds functions that call arrays, etc
include '_inc/head.php';//Begin Document
//include '_inc/header.php';//Begin Content
?>
<article class="container box style3">
<header>
<img src="_img/icons/icon_lg-max-o-matic2.png" alt="php icon">
<h2><?=NAME_SITE?></h2>
<p>Spam Survey</p>
</header>
<?php
$to = "chezshire#gmail.com";
$subject="Spam Survey";
//----- end conf ----- //
// define variables and set to empty values
$nameErr = $emailErr = $spamErr = "";
$userName = $userEmail = $userMessage = $website = "";
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
if (empty($_POST["userName"]))
{$nameErr = "* Name is required";}
else
{$name = testInput($_POST["userName"]);}
if (empty($_POST["userEmail"]))
{$emailErr = "* Email is required";}
else
{$email = testInput($_POST["userEmail"]);}
if (empty($_POST["spamErr"]))
{$emailErr = "* You must select an option";}
else
{$email = testInput($_POST["userEmail"]);}
if (empty($_POST["userMessage"]))
{$comment = "";}
else
{$comment = testInput($_POST["userMessage"]);}
}
if(isset($_POST['userName']))
{//data is submitted, show it
//echo $_POST['userName'];
$text = 'From: ' . $_POST['userName'] . PHP_EOL;
//$text .= $_POST['Comments']; //add on to text
$text .= process_post(); // uses proces_post to handle comments and stuff
$from = $_POST['userEmail'];
/*
echo '<pre>';
var_dump($_POST);
echo '</pre>';
*/
//domain spoofing controls
$headers = 'From: noreply#max-o-matic.com' . PHP_EOL . //from where formhandler sits
'Reply-To: ' . $from . PHP_EOL . //where replies are to go to
'X-Mailer: PHP/' . phpversion();
mail($to, $subject, $text, $headers); //from becomes headers
echo '<div class="row">
<div class="12u">
<p>Thanxs!</p>
<p>
<br />RESET
</p>
</div>
</div>
</article>
';
/*
echo '<pre>';
var_dump($_POST);
echo '</pre>';
*/
}else{//no data, show form
echo '
<form action="' . THIS_PAGE . '" method="post">
<div class="row half">
<div class="6u">
<input type="text" class="text" name="userName" placeholder="Name?" required autofocus />
<span class="error"><?php echo $nameErr;?></span>
</div>
<div class="6u">
<input type="text" class="text" name="userEmail" placeholder="Email" required />
<span class="error"><?php echo $emailErr;?></span>
</div>
</div>
<div class="row half">
<div class="6u">
Do you like spam?<br />
<input type="radio" name="Please_Spam_Me" value="YES!" required value="1" />Yes<br />
<input type="radio" name="Please_Spam_Me" value="NO!" />No<br />
<span class="error"><?php echo $spamErr;?>
</div>
<div class="6u">
How much Spam is too much?<br />
<input type="checkbox" name="checkbox-group" class="group-required" id="checkbox-group-id" value="6+" >6 or more<br />
<input type="checkbox" name="checkbox-group" value="2+">2 to 5<br />
<input type="checkbox" name="checkbox-group" value="Any">ANY<br /><br />
</div>
</div>
<!--For Winnie the Pooh -->
<input id="website" name="website" type="text" value"Website" />
<div class="row half">
<div class="12u">
<textarea name="userMessage" placeholder="What is your opinion on Spam?"></textarea>
</div>
</div>
<div class="row">
<div class="12u">
<ul class="actions">
<li>SEND!</li>
<input type="submit" />
</ul>
<p class="vSmall">
* Please note, instead of a reCaptcha I build my own \'honeypot\' from scratch.
</p>
</div>
</div>
</form>
</article>
';
}
function testInput($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
// this is a function
function process_post()
{//loop through POST vars and return a single string
$myReturn = ''; //set to initial empty value
foreach($_POST as $varName=> $value)//$_POST is an array
{#loop POST vars to create JS array on the current page - include email
$strippedVarName = str_replace("_"," ",$varName);#remove underscores
if(is_array($_POST[$varName]))
{#checkboxes are arrays, and we need to collapse the array to comma separated string!
$myReturn .= $strippedVarName . ": " . implode(",",$_POST[$varName]) . PHP_EOL;
}else{//not an array, create line
$myReturn .= $strippedVarName . ": " . $value . PHP_EOL;
}
}
return $myReturn;
}
include "_inc/footer.php";//End Content/Document
?>
If you're trying to use HTML5 stuffs then you need the HTML5 doctype. Place this at the start of your output and see what happens:
<!DOCTYPE html>
Also, typo value"Website" should be value="Website"

How to configure WAMP and Smtp server

I have spent a significant time looking for an answer, and tried every solution without success :/
Basically I want to use wamp server to create contact form that will be sent to my mail address.
I have wamp running but for the life of me I can't figure out why I wouldn't receive the mails, I either get the 404 page when submitting the form, or lately "Warning: mail(): SMTP server response: 553 sorry, that domain isn't in my list of allowed rcpthosts".
I am now looking for a solution that will at least send the form to my address, whether it's secured or not I just want to see an actual mail successfully sent.
Thanks !
edit: here is the code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title> Contact Form</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
<div id="page-wrap">
<div id="contact-area">
<form method="post" action="contactengine.php">
<label for="Name">Name:</label>
<input type="text" name="Name" id="Name" />
<label for="Email">Email:</label>
<input type="text" name="Email" id="Email" />
<label for="Message">Message:</label><br />
<textarea name="Message" rows="20" cols="20" id="Message"> </textarea>
<input type="submit" name="submit" value="Submit" class="submit-button" />
</form>
<div style="clear: both;"></div>
</div>
</div>
</body>
</html>
--then the contact engine--
<?php
$EmailFrom = "myadress#mail.com";
$EmailTo = "myadress#mail.com";
$Subject = "Nice & Simple Contact Form by CSS-Tricks";
$Name = Trim(stripslashes($_POST['Name']));
$Tel = Trim(stripslashes($_POST['Tel']));
$Email = Trim(stripslashes($_POST['Email']));
$Message = Trim(stripslashes($_POST['Message']));
// validation
$validationOK=true;
if (!$validationOK) {
print "<meta http-equiv=\"refresh\" content=\"0;URL=error.htm\">";
exit;
}
// prepare email body text
$Body = "";
$Body .= "Name: ";
$Body .= $Name;
$Body .= "\n";
$Body .= "Tel: ";
$Body .= $Tel;
$Body .= "\n";
$Body .= "Email: ";
$Body .= $Email;
$Body .= "\n";
$Body .= "Message: ";
$Body .= $Message;
$Body .= "\n";
// send email
$success = mail($EmailTo, $Subject, $Body, "From: <$EmailFrom>");
// redirect to success page
if ($success){
print "<meta http-equiv=\"refresh\" content=\"0;URL=contactthanks.php\">";
}
else{
print "<meta http-equiv=\"refresh\" content=\"0;URL=error.htm\">";
}
?>
--then the thanks message--
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Strict//EN">
<head>
<title>A Nice & Simple Contact Form</title>
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
<div id="page-wrap">
<img src="images/title.gif" alt="A Nice & Simple Contact Form" />
<p>By CSS-Tricks</p>
<br /><br />
<h1>Your message has been sent!</h1><br />
<p>Back to Contact Form</p>
</div>
<script src="http://www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-68528-29";
urchinTracker();
</script>
</body>
</html>
Windows does not come with a Mail Server so just calling mail() will work as far as php is concerned but the mail goes nowhere.
You either need to install a mail server or use something like the PHPMailer library to allow you to send SMTP mails via something like Yahoo or Google.

PHP mail function has stopped working

I have created a contact form that sends an email to the website administrator and to the person who filled out the contact form. It was working fine and I have just come back to it to do some more testing and it has stopped sending. To my knowledge I've not changed any of the code. I can't figure out what is wrong with it. Can someone help? Below is the code for the three files I'm using.
This is the contact form file:
<div id="contact-form" class="contact-form">
<div class="rounded-box">
<div class="rounded-box-title">
<h3>Ask for a call back</h3>
<img src="<?php echo get_bloginfo('url') ?>/images-default/br_next.png"/>
</div><!-- .rounded-box-title -->
<?php
$cf = array();
if(isset($_SESSION['cf_returndata'])){
$cf = $_SESSION['cf_returndata'];
?>
<div id="success" class="success"><?php echo ($cf['success']); ?></div>
<script>
$("#success").delay(6000).slideUp();
</script>
<?php
}
?>
<div class="required-text-line">
<span class="required">*</span><span class="required-text">indicates required field</span>
</div>
<form name="contact-form" onsubmit="return validateForm()" action="<?php bloginfo('url'); ?>/wp-content/themes/example/contact-form-send.php" method="POST">
<fieldset>
<label for="fname"><span class="required">*</span>First name:</label></br>
<input type="text" name="fname" id="fname" onblur="return validateFirstName()" value="" />
<span class="error" id="fnameError" style="display: none;"></span>
<script>
$("#fname").blur(function(){
$("#fnameError").delay(6000).slideUp();
})
</script>
</fieldset>
<fieldset>
<label for="lname"><span class="required">*</span>Last name:</label></br>
<input type="text" name="lname" id="lname" onblur="return validateLastName()" value="" />
<span class="error" id="lnameError" style="display: none;"></span>
<script>
$("#lname").blur(function(){
$("#lnameError").delay(6000).slideUp();
})
</script>
</fieldset>
<fieldset>
<label for="email"><span class="required">*</span>Email:</label></br>
<input type="text" name="email" id="email" onblur="return validateEmail()" value="" />
<span class="error" id="emailError" style="display: none;"></span>
<script>
$("#email").blur(function(){
$("#emailError").delay(6000).slideUp();
})
</script>
</fieldset>
<fieldset>
<label for="tel"><span class="required">*</span>Telephone:</label></br>
<input type="text" name="tel" id="tel" onblur="return validateTel()" value="" />
<span class="error" id="telError" style="display: none;"></span>
<script>
$("#tel").blur(function(){
$("#telError").delay(6000).slideUp();
})
</script>
</fieldset>
<fieldset>
<label for="message"><span class="required">*</span>Message:</label></br>
<textarea name="message" id="message" onblur="return validateMessage()" ></textarea>
<span class="error" id="messageError" style="display: none;"></span>
<script>
$("#message").blur(function(){
$("#messageError").delay(6000).slideUp();
})
</script>
</fieldset>
<fieldset id="hiddenfield">
<label for="hidden"></label>
<textarea name="hidden" id="hidden" ></textarea>
</fieldset>
<input type="submit" value="Submit" id="submit" />
<script>
$("form").submit(function(){
$(".error").delay(6000).slideUp();
})
</script>
</form>
<?php unset($_SESSION['cf_returndata']); ?>
</div><!-- .rounded-box -->
</div><!-- .contact-form -->
This is the send PHP file:
<?php
if( isset($_POST) ){
if (empty($_POST ['hidden'])) {
$fname = htmlspecialchars($_POST ['fname']);
$lname = htmlspecialchars($_POST ['lname']);
$email = htmlspecialchars($_POST ['email']);
$tel = htmlspecialchars($_POST ['tel']);
$message = htmlspecialchars($_POST ['message']);
$to = "example#gmail.com";
$subject = "Callback request";
$body = "
<html>
<head>
</head>
<header style='padding:10px'>
<a href='http://example.com'>
<img src='http://example.com/images-default/example-logo.png' alt='example.com'>
</a>
</header>
<body style='border-top:2px solid #91448D;margin-top:15px'>
<p>You have recieved an message through the callback request form on the website.</p>
<p><strong>Name: </strong>{$fname} {$lname} </p>
<p><strong>Email: </strong>{$email} </p>
<p><strong>Telephone: </strong>{$tel} </p>
<p><strong>Message: </strong>{$message}</p>
</body>
</html>
";
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= 'From: example <info#example.com>' . "\r\n";
$headers .= 'Reply-To: info#example.com' . "\r\n";
mail ( //email to info#example.com
$to,
$subject,
$body,
$headers
);
$subject2 = "Thanks for your enqiry";
$body2 = "
<html>
<head>
</head>
<header style='padding:10px'>
<a href='http://example.com'>
<img src='http://example.com/images-default/example-logo.png' alt='example.com'>
</a>
</header>
<body style='border-top:2px solid #91448D;margin-top:15px'><br/>
<p style='margin-bottom:1em'>Hi {$fname},<br/><br/>
Thanks for enquiring about private maths tuition with <a href='http://example.com'>example.com</a>.<br/><br/>
We'll get back to you within 24 hours for a chat about your child's learning needs.<br/><br/>
Regards,<br/><br/>
<strong>Kathy</strong><br/>
<a href='http://example.com'>example.com</a> founder<br/>
tel: 01582 472060<br/>
email: <a href='mailto:info#example.com'>info#example.com</a></p>
</body>
</html>
";
mail ( //email to enquiror
$email,
$subject2,
$body2,
$headers
);
$success = "Thank you for your enquiry. We'll get back to you within 24 hours.";
$returndata = array (
'success' => $success
);
session_start();
$_SESSION['cf_returndata'] = $returndata;
header('location: ' . $_SERVER['HTTP_REFERER']);
}
}
?>
This is the javascript validation file:
function validateFirstName(){
if (
document.getElementById('fname').value == "") {
document.getElementById('fnameError').style.display = "block";
document.getElementById('fnameError').innerHTML = "Please enter your first name";
return false;
}
else {
document.getElementById('fnameError').style.display = "none";
return true;
}
}
function validateLastName(){
if (
document.getElementById('lname').value == "") {
document.getElementById('lnameError').style.display = "block";
document.getElementById('lnameError').innerHTML = "Please enter your last name";
return false;
}
else {
document.getElementById('lnameError').style.display = "none";
return true;
}
}
function validateEmail(){
var re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if (
re.test(document.getElementById('email').value)){
document.getElementById('emailError').style.display = "none";
return true;
}
else {
if (
document.getElementById('email').value == "") {
document.getElementById('emailError').style.display = "block";
document.getElementById('emailError').innerHTML = "Please enter your email address";
return false;
}
else {
document.getElementById('emailError').style.display = "block";
document.getElementById('emailError').innerHTML = "Please enter a valid email address";
return false;
}
}
}
function validateTel(){
var re = /(((\+44)? ?(\(0\))? ?)|(0))( ?[0-9]{3,4}){3}/;
if (
re.test(document.getElementById('tel').value)){
document.getElementById('telError').style.display = "none";
return true;
}
else {
if (
document.getElementById('tel').value == "") {
document.getElementById('telError').style.display = "block";
document.getElementById('telError').innerHTML = "Please enter your phone number";
return false;
}
else {
document.getElementById('telError').style.display = "block";
document.getElementById('telError').innerHTML = "Please enter a valid phone number";
return false;
}
}
}
function validateMessage(){
if (
document.getElementById('message').value == "") {
document.getElementById('messageError').style.display = "block";
document.getElementById('messageError').innerHTML = "Please enter a message";
return false;
}
else {
document.getElementById('messageError').style.display = "none";
return true;
}
}
function validateForm(){
// Set error catcher
var error = 0;
// Check first name
if(!validateFirstName(document.getElementById('fname').value)){
document.getElementById('fnameError').style.display = "block";
error++;
}
// Check last name
if(!validateLastName(document.getElementById('lname').value)){
document.getElementById('lnameError').style.display = "block";
error++;
}
// Validate email
if(!validateEmail(document.getElementById('email').value)){
document.getElementById('emailError').style.display = "block";
error++;
}
// Validate phone number
if(!validateTel(document.getElementById('tel').value)){
document.getElementById('telError').style.display = "block";
error++;
}
if(!validateMessage(document.getElementById('message').value)){
document.getElementById('messageError').style.display = "block";
error++;
}
if (
!document.getElementById('hidden').value == "") {
error++;
}
if(error > 0){
return false;
}
}

How do I send a multiple field form to email with multiple variables?

I've spent most of today and all of yesterday just trying to get a simple, basic send-to-email PHP code to work. Here is the code I've tried putting together myself after extensively researching, checking, and editing based on a lot of other threads I've read on this website and on other sites.
<?php
$to='dustedpages#gmail.com';
$subject='Commission Inquiry';
$email = $_REQUEST['Email'] ;
$headers = "From: $email";
$sent = mail($to, $subject, $message, $headers) ;
$message="Name: ".$name. "\r\n" . "Email: " .$email . "\r\n" . "Username: " .$user . "\r\n" . "Type: ".$position. "\r\n" . "Add-Ons: ".$addons. "\r\n" . "Price: ".$price. "\r\n" . "Brief Description: ".$briefdesc;
$name=$_POST['FirstName'],['LastName'];
$email=$_POST['Email'];
$user=$_POST['User'];
$position=$_POST['position'];
$addons=$_POST['cat'],['dog'];
$price=$_POST['price'];
$desc=$_POST['briefdesc'];
if($sent)
{print "Your mail was sent successfully. Please be patient and the artist will contact you soon. Thanks!"; }
else
{print "We encountered an error sending your mail"; }
?>
There is actually a LOT more form data than just that basic information, but I cannot even get the basic information to show up. For the portion of html codes it is pulling from, here is some of what it looks like.
<!--NAME-->
</li> <li id="li_2" >
<label class="description" for="element_2">Name </label>
<span>
<input onkeypress="return handleEnter(this, event)" id="element_2_1" name="FirstName" class="element text" maxlength="255" size="14" value=""/>
<label>First</label>
</span>
<span>
<input onkeypress="return handleEnter(this, event)" id="element_2_2" name="LastName" class="element text" maxlength="255" size="18" value=""/>
<label>Last</label>
</span>
<p class="guidelines" id="guide_2"><small>Please fill this in as the name I will see on Paypal.</small></p>
<!--EMAIL-->
</li> <li id="li_1" >
<label class="description" for="element_1">Email </label>
<div>
<input onkeypress="return handleEnter(this, event)" id="element_1" name="Email" class="element text medium" type="text" maxlength="255" value=""/>
</div>
<p class="guidelines" id="guide_1"><small>Your Paypal email</small></p>
<!--USERNAME-->
</li> <li id="li_3" >
<label class="description" for="element_3">DA/Tumblr Username </label>
<div>
<input onkeypress="return handleEnter(this, event)" id="element_3" name="User" class="element text medium" type="text" maxlength="255" value=""/>
</div>
<p class="guidelines" id="guide_3"><small>If you have an account on either Deviantart or Tumblr and wish to be credited in the commission description, please note it here.</small></p>
</li>
<p>
<!--POSITION TYPE-->
</li> <li id="li_26" >
<label class="description" for="element_26">Comm. Type </label>
<div>
<select class="element select medium" id="element_26" name="position">
<option value="" selected="selected"></option>
<option value="1" >Bust</option>
<option value="2" >Waist</option>
<option value="3" >Full-Body</option>
</select>
</div>
<p class="guidelines" id="guide_26">
<small>Please choose what position you wish for your character(s) to be viewed from. Price will change depending on what type you choose.</small></p>
<!--ADD ONS-->
</li> <li id="li_27" >
<label class="description" for="element_27" name="addons">Add-Ons </label>
<span>
<input name="cat" type="checkbox" onClick="return KeepCount()">
+1 Character<br>
<input name="dog" type="checkbox" onClick="return KeepCount()">
+2 Characters
I have multiple fields (such as the First and Last Name) that I need to be one single variable in the email code, and I need to be able to display all of the filled out form fields in an email. I can't even get more than one variable to show up at this point.
Also the form itself includes selects, checkboxes, textareas, and image uploads. I haven't even gotten to that point - I'm just trying to make some of the basic information show up right now. I'm very familiar with HTML and Javascript, just not so much PHP, though I've worked with it before. Some of the form data is used in Javascript code on the same page as the HTML, also. The actual PHP data is on a separate file that my form pulls from.
I think what's happening is you're attempting to use variables before they have the value you would like. Try something like the following and let me know how it goes.
<?php
$to = 'dustedpages#gmail.com';
$subject = 'Commission Inquiry';
$headers = "From: $email";
$fname = $_POST['FirstName'];
$lname = $_POST['LastName'];
$email = $_POST['Email'];
$user = $_POST['User'];
$position = "CHANGE-ME";
$addons = "CHANGE-ME";
$price = "CHANGE-ME";
$briefdesc = "CHANGE-ME";
$message = "Name: ".$fname.", ".$lname."\r\n";
$message .= "Email: $email \r\n";
$message .= "Username: $user \r\n";
$message .= "Type: $position \r\n";
$message .= "Add-Ons: $addons \r\n";
$message .= "Price: $price \r\n";
$message .= "Brief Description: $briefdesc \r\n";
$sent = mail($to, $subject, $message, $headers);
if($sent) {
echo "Success";
}
else {
echo "Failure";
}
?>