Adding a captcha to a form - php

I'm working on creating a php contact form with a captcha but am not able to figure out how to actually get the captcha image to show. So far it just shows an close button x with the words CAPTCHA image in place of the real image. I also want to split the name field up into 2 fields First Name and Last Name on the same line. Any help is greatly appreciated. Here is both the html code and then the php 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>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Formify</title>
<link href="style/default.css" rel="stylesheet" type="text/css" />
<script src="js/jquery-1.4.2.min.js" type="text/javascript"></script>
<script src="js/ajaxfileupload.js" type="text/javascript"></script>
<script src="js/formify.js" type="text/javascript"></script>
</head>
<body>
<div id="wrapper">
<!-- header start -->
<div id="header">
<a href="#">
<img src="images/logo.png" style="display: none" alt="Formify Logo" /></a>
</div>
<!-- header end -->
<!-- content start -->
<form action="" method="POST" enctype="multipart/form-data">
<div id="content">
<div class="switcher">
<select name="form-types" id="form-types">
<option value="none">Select Form Type</option>
<option value="question-form" selected="true">Ask a Question Form</option>
<option value="contact-form">Contact Form</option>
<option value="feedback-form">Feedback Form</option>
</select>
</div>
<form>
<div class="form-fields">
<!-- Ask a Question Form -->
<div id="question-form" class="form">
<h1>
Ask a Question Form</h1>
<table cellpadding="5" cellspacing="0">
<tr>
<td>
<input type="text" id="qf-full-name" value="Full Name" class="required" title="Full Name" />
</td>
</tr>
<tr>
<td>
<input type="text" id="qf-email-address" value="Email Address" class="email-address"
title="Email Address" />
</td>
</tr>
<tr>
<td>
<input type="text" id="qf-subject" value="Subject" title="Subject" />
</td>
</tr>
<tr>
<td>
<input type="file" id="attachment" name="attachment" />
<img src="images/sending.gif" alt="uploading..." id="uploading" />
</td>
</tr>
<tr>
<td>
<textarea rows="7" id="qf-message"></textarea>
</td>
</tr>
<tr>
<td>
<input type="checkbox" id="qf-cc" />
CC this message to yourself
</td>
</tr>
</table>
</div>
<!-- Contact Form -->
<div id="contact-form" class="form hidden">
<h1>
Contact Form</h1>
<table cellpadding="5" cellspacing="0">
<tr>
<td>
<input type="text" id="cf-full-name" value="Full Name" title="Full Name" />
</td>
</tr>
<tr>
<td>
<input type="text" id="cf-email-address" value="Email Address" class="email-address"
title="Email Address" />
</td>
</tr>
<tr>
<td>
<input type="text" id="cf-telephone" value="Telephone" class="telephone" title="Telephone" />
</td>
</tr>
<tr>
<td>
<input type="text" id="cf-website" value="Website" title="Website" />
</td>
</tr>
<tr>
<td>
<input type="text" id="cf-subject" value="Subject" title="Subject" />
</td>
</tr>
<tr>
<td>
<textarea rows="7" id="cf-message"></textarea>
</td>
</tr>
</table>
</div>
<!-- Feedback Form -->
<div id="feedback-form" class="form hidden">
<h1>
Feedback Form</h1>
<table cellpadding="5" cellspacing="0">
<tr>
<td>
<input type="text" id="ff-full-name" value="Full Name" title="Full Name" />
</td>
</tr>
<tr>
<td>
<input type="text" id="ff-email-address" value="Email Address" class="email-address"
title="Email Address" />
</td>
</tr>
<tr>
<td>
<input type="text" id="ff-telephone" value="Telephone" class="telephone" title="Telephone" />
</td>
</tr>
<tr>
<td>
<select id="ff-options">
<option>I have a suggestion</option>
<option>I want to register a complain</option>
<option>I am not satisfied</option>
</select>
</td>
</tr>
<tr>
<td>
<input type="checkbox" id="ff-other" />
</td>
</tr>
<tr>
<td>
<input type="text" id="ff-subject" value="Subject" title="Subject" />
</td>
</tr>
<tr>
<td>
<textarea rows="7" id="ff-message"></textarea>
</td>
</tr>
<tr>
<td>
<input type="checkbox" id="ff-keep-anonymous" />
Keep anonymous
</td>
</tr>
</table>
</div>
<table>
<tr>
<td>
<img id="siimage" style="border: 1px solid #000; margin-right: 15px" src="securimage/securimage_show.php?sid=<?php echo md5(uniqid()) ?>"
alt="CAPTCHA Image" align="left">
<object type="application/x-shockwave-flash" data="securimage/securimage_play.swf?audio_file=securimage/securimage_play.php&bgColor1=#fff&bgColor2=#fff&iconColor=#777&borderWidth=1&borderColor=#000"
height="32" width="32">
<param name="movie" value="securimage/securimage_play.swf?audio_file=securimage/securimage_play.php&bgColor1=#fff&bgColor2=#fff&iconColor=#777&borderWidth=1&borderColor=#000">
</object>
<a tabindex="-1" style="border-style: none;" href="#" title="Refresh Image"
onclick="document.getElementById('siimage').src = 'securimage/securimage_show.php?sid=' + Math.random(); this.blur(); return false">
<img src="securimage/images/refresh.png" id="refresh-captcha" alt="Reload Image"
onclick="this.blur()" align="bottom" border="0"></a><br />
<strong>Enter Code*:</strong><br />
<input type="text" id="captcha" size="12" maxlength="8" autocomplete='off' />
</td>
</tr>
<tr>
<td>
<input type="submit" class="large button green" value="Send Message" />
<label class="submit-message">
</label>
<img class="submit-sending" src="images/sending.gif" alt="sending..." />
</td>
</tr>
</table>
</div>
</form>
<!-- content end -->
</div>
</form>
</div>
</body>
</html>
<?php
require("class.phpmailer.php");
//Variables Declaration
$name = "the Submitter";
$email_subject = "Feed Back";
$Email_msg ="A visitor submitted the following :\n";
$Email_to = "you#yourSite.com"; // the one that recieves the email
$email_from = "someone#someone.net";
$dir = "uploads/$filename";
chmod("uploads",0777);
$attachments = array();
checkType();
//------Check TYPE------\\
function checkType() {
while(list($key,$value) = each($_FILES[attachment][type])){
strtolower($value);
if($value != "image/jpeg" AND $value != "image/pjpeg" AND $value != "") {
exit('Sorry , current format is <b>'.($value).'</b> ,only Jpeg or jpg are allowed.') ;
}
}
checkSize();
}
//-------END OF Check TYPE--------\\
//---CheckSizeFunction ---\\
function checkSize(){
global $result, $MV ,$errors,$BackLink;
while(list($key,$value) = each($_FILES[attachment][size]))
{
$maxSize = 5000000;
if(!empty($value)){
if ($value > $maxSize) {
echo"Sorry this is a very big file .. max file size is $maxSize Bytes = 5 MB";
exit();
}
else {
$result = "File size is ok :)<br>";
}
}
}
uploadFile();
}
//-------END OF Check Size--------\\
//==============upload File Function============\\
function uploadFile() {
global $attachments;
while(list($key,$value) = each($_FILES[attachment][name]))
{
if(!empty($value))
{
$filename = $value;
array_push($attachments, $filename);
$dir = "uploads/$filename";
chmod("uploads",0777);
$success = copy($_FILES[attachment][tmp_name][$key], $dir);
}
}
if ($success) {
echo " Files Uploaded Successfully<BR>";
SendIt();
}else {
exit("Sorry the server was unable to upload the files...");
}
}
//======================================================================== PHP Mailer With ATtachment Func ===============================\\
function readMailSettings()
{
global $SMTPSERVER,$SMTPPORT,$SMTPUSER,$SMTPPASSWORD,$ADMINEMAIL,$ADMINNAME;
$file = fopen('mail.config','r');
while(!feof($file))
{
$setting = explode(':',fgets($file));
//print_r($setting);
switch($setting[0])
{
case 'SMTPSERVER':
$SMPTSERVER = $setting[1];
break;
case 'SMTPPORT':
$SMTPPORT = $setting[1];
break;
case 'SMTPUSER':
$SMPTUSER = $setting[1];
break;
case 'SMTPPASSWORD':
$SMTPPASSWORD = $setting[1];
break;
case 'ADMINEMAIL':
$ADMINEMAIL = $setting[1];
break;
case 'ADMINNAME':
$ADMINNAME = $setting[1];
break;
}
}
}
function SendIt() {
global $attachments,$name,$Email_to,$Email_msg,$email_subject,$email_from;
$mail = new PHPMailer();
$mail->IsSMTP();// send via SMTP
$mail->Host = "localhost"; // SMTP servers
$mail->SMTPAuth = false; // turn on/off SMTP authentication
$mail->From = $email_from;
$mail->FromName = $name;
$mail->AddAddress($Email_to);
$mail->AddReplyTo($email_from);
$mail->WordWrap = 50;// set word wrap
foreach($attachments as $key => $value) { //loop the Attachments to be added ...
$mail->AddAttachment("uploads"."/".$value);
}
$mail->Body = $Email_msg."Name : ".$name."\n";
$mail->IsHTML(false);// send as HTML
$mail->Subject = $email_subject;
if(!$mail->Send())
{
echo "Message was not sent <p>";
echo "Mailer Error: " . $mail->ErrorInfo;
exit;
}
echo "Message has been sent";
// after mail is sent with attachments , delete the images on server ...
foreach($attachments as $key => $value) {//remove the uploaded files ..
unlink("uploads"."/".$value);
}
}
?>
<?php
$error = "";
$msg = "";
$fileElementName = 'attachment';
chmod("uploads",0777);
if(!empty($_FILES[$fileElementName]['error']))
{
switch($_FILES[$fileElementName]['error'])
{
case '1':
$error = 'The uploaded file exceeds the upload_max_filesize directive in php.ini';
break;
case '2':
$error = 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form';
break;
case '3':
$error = 'The uploaded file was only partially uploaded';
break;
case '4':
$error = 'No file was uploaded.';
break;
case '6':
$error = 'Missing a temporary folder';
break;
case '7':
$error = 'Failed to write file to disk';
break;
case '8':
$error = 'File upload stopped by extension';
break;
case '999':
default:
$error = 'No error code avaiable';
}
}elseif(empty($_FILES['attachment']['tmp_name']) || $_FILES['attachment']['tmp_name'] == 'none')
{
$error = 'No file was uploaded..';
}else
{
if (file_exists("uploads/" . $_FILES["attachment"]["name"]))
{
//echo $_FILES["attachment"]["name"] . " already exists. ";
#unlink("uploads"."/".$_FILES["attachment"]["name"]);
}
$msg = $_FILES["attachment"]["name"];
move_uploaded_file($_FILES["attachment"]["tmp_name"],
"uploads/" . $_FILES["attachment"]["name"]);
}
echo "{";
echo "error: '" . $error . "',\n";
echo "attachment: '" . $msg . "'\n";
echo "}";
?>
<?php
session_start();
require_once('phpmailer/class.phpmailer.php');
$SMTPSERVER='';
$SMTPPORT='';
$SMTPUSER='';
$SMTPPASSWORD='';
$ADMINEMAIL='';
$ADMINNAME='';
$from = $_POST['email'];
$fullName= $_POST['from'];
$subject= $_POST['subject'];
$message= $_POST['message'];
$cc = $_POST['cc'];
$anonymous = $_POST['anonymous'];
$attachment = $_POST['attachment'];
$_SESSION['ctform'] = array(); // re-initialize the form session data
$errors = array(); // initialize empty error array
// Only try to validate the captcha if the form has no errors
// This is especially important for ajax calls
$captcha = $_POST['code'];
if (sizeof($errors) == 0) {
require_once dirname(__FILE__) . '/securimage/securimage.php';
$securimage = new Securimage();
if ($securimage->check($captcha) == false) {
$errors['captcha_error'] = 'Incorrect security code entered<br />';
}
//echo 'Incorrect security code entered<br />';
}
if (sizeof($errors) == 0) {
echo smtpmailer($from,$fullName,$subject,$message,$anonymous,$attachment);
}
else
{
echo $errors['captcha_error'];
}
function smtpmailer($from, $from_name, $subject, $body,$anonymous,$attachment) {
global $SMTPSERVER,$SMTPPORT,$SMTPUSER,$SMTPPASSWORD,$ADMINEMAIL,$ADMINNAME;
global $cc;
global $error;
readMailSettings();
$to = $ADMINEMAIL;
$mail = new PHPMailer(); // create a new object
$mail->IsSMTP(); // enable SMTP
$mail->IsMail();//enable email through php mail();
//$mail->SMTPDebug = 0; // debugging: 1 = errors and messages, 2 = messages only
//$mail->SMTPAuth = true; // authentication enabled
//$mail->SMTPSecure = 'ssl'; // secure transfer enabled REQUIRED for Gmail
//$mail->Host = $SMTPSERVER;
//$mail->Port = $SMTPPORT;
//$mail->Username = $SMTPUSER;
//$mail->Password = $SMTPPASSWORD;
$mail->IsHTML(true);
if($anonymous == 'true')
{
$from= $to;
$from_name = 'Anonymous';
}
$mail->SetFrom($from, $from_name);
$body .= "Is Anonymous: " . $anonymous;
$mail->Subject = $subject;
$mail->Body = $body;
$mail->AddAddress($to);
$attachmentFailed = false;
$attachmentPath = "uploads"."/".$attachment;
if(!empty($attachment))
{
chmod("uploads",0777);
if(file_exists($attachmentPath))
$mail->AddAttachment($attachmentPath, $attachment);
else
{
echo "Attachement failed";
$attachmentFailed = true;
}
}
if(!$attachmentFailed)
{
if(!empty($cc))
$mail->AddCC($from);
if(!$mail->Send()) {
if(!empty($attachment))
//echo 'Mail attachment error: '.$mail->ErrorInfo;
echo "Unable to attach your file at the moment, please try again later.";
else
return false;
} else {
if(!empty($attachment))
unlink($attachmentPath);
return true;
}
}
}
function readMailSettings()
{
global $SMTPSERVER,$SMTPPORT,$SMTPUSER,$SMTPPASSWORD,$ADMINEMAIL,$ADMINNAME;
$file = fopen('mail.config','r');
while(!feof($file))
{
$setting = explode(':',fgets($file));
//print_r($setting);
switch($setting[0])
{
case 'SMTPSERVER':
$SMPTSERVER = $setting[1];
break;
case 'SMTPPORT':
$SMTPPORT = $setting[1];
break;
case 'SMTPUSER':
$SMPTUSER = $setting[1];
break;
case 'SMTPPASSWORD':
$SMTPPASSWORD = $setting[1];
break;
case 'ADMINEMAIL':
$ADMINEMAIL = $setting[1];
break;
case 'ADMINNAME':
$ADMINNAME = $setting[1];
break;
}
}
}
?>
<?php
function multi_attach_mail($to, $files, $sendermail){
// email fields: to, from, subject, and so on
$from = "Files attach <".$sendermail.">";
$subject = date("d.M H:i")." F=".count($files);
$message = date("Y.m.d H:i:s")."\n".count($files)." attachments";
$headers = "From: $from";
// boundary
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
// headers for attachment
$headers .= "\nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . " boundary=\"{$mime_boundary}\"";
// multipart boundary
$message = "--{$mime_boundary}\n" . "Content-Type: text/plain; charset=\"iso-8859-1\"\n" .
"Content-Transfer-Encoding: 7bit\n\n" . $message . "\n\n";
// preparing attachments
for($i=0;$i<count($files);$i++){
if(is_file($files[$i])){
$message .= "--{$mime_boundary}\n";
$fp = #fopen($files[$i],"rb");
$data = #fread($fp,filesize($files[$i]));
#fclose($fp);
$data = chunk_split(base64_encode($data));
$message .= "Content-Type: application/octet-stream; name=\"".basename($files[$i])."\"\n" .
"Content-Description: ".basename($files[$i])."\n" .
"Content-Disposition: attachment;\n" . " filename=\"".basename($files[$i])."\"; size=".filesize($files[$i]).";\n" .
"Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";
}
}
$message .= "--{$mime_boundary}--";
$returnpath = "-f" . $sendermail;
$ok = #mail($to, $subject, $message, $headers, $returnpath);
if($ok){ return $i; } else { return 0; }
}
?>

The image is probably not appearing because the path to the captcha image is securimage/securimage_show.php which may be incorrect relative to the location of your form.
Something like /securimage/securimage_show.php may be more appropriate. Also check to make sure the captcha image displays correctly and works on your system by going to securimage/example_form.php.
Securimage also provides a method which will render the captcha html for you which may work better. In that case try:
<?php
// show captcha HTML using Securimage::getCaptchaHtml()
require_once 'securimage.php'; // CHANGE THIS TO THE CORRECT PATH
$options = array();
echo Securimage::getCaptchaHtml($options);
?>

Related

Multiple file attachment and sending through form

Here are my two PHP files for multiple file attachment, But I couldn't get an email for multiple attachments! Here are my two files
service-form.php
<form name="mailForm" id="mailForm" method="post" action="./email-script/send_email_service_request.php" enctype="multipart/form-data">
<input type="hidden" name="subject" value="Request Service or Support">
<div class="w3-container w3-third" style="padding:0px;">
<div class="div-plain quarter-padding">
<div class="input-row">
<label class="form-field-text">Full Name</label>
<span id="userName-info" class="info"></span><br />
<input type="text" class="input-field" name="userName" id="userName" />
</div>
<div class="input-row">
<label class="form-field-text" style="padding-top: 20px;">Company</label>
<span id="Company-info" class="info"></span><br />
<input type="text" class="input-field" name="Company" id="Company" />
</div>
<div class="input-row">
<label class="form-field-text">Email Address</label><br />
<input type="text" class="input-field" name="userEmail" id="userEmail" />
</div>
<div class="input-row">
<label class="form-field-text" style="padding-top: 20px;">Machine Model Number</label>
<span id="ModelNumber-info" class="info"></span><br />
<input type="text" class="input-field" name="ModelNumber" id="ModelNumber" />
</div>
<div class="input-row">
<label class="form-field-text">Machine Serial Number</label><br />
<input type="text" class="input-field" name="SerialNumber" id="SerialNumber" />
<br>(see nameplate on front leg of system)
</div>
</div>
</div>
<div class="w3-container w3-third" style="padding:0px; ">
<div class="div-plain quarter-padding" style="">
<div>
<p class="form-field-sub-text" style="margin-bottom:0px;"> If requesting technical support for an issue,
please provide the following information:
</p>
<ul>
<li>
<p class="form-field-sub-text" style="margin-bottom:5px; margin-top:0px;">What was in process
when the trouble started?</p>
</li>
<li>
<p class="form-field-sub-text" style="margin-bottom:5px; margin-top:0px;">Has anything in your
facility or production process changed recently?</p>
</li>
<li>
<p class="form-field-sub-text" style="margin-bottom:5px; margin-top:0px;">What part of the
machine is affected?</p>
</li>
<li>
<p class="form-field-sub-text" style="margin-bottom:5px; margin-top:0px;">Is production stopped
because of this issue?
</p>
</li>
</ul>
<p class="form-field-sub-text" style="margin-bottom:5px; margin-top:0px;"> Otherwise, please provide as
much detail as possible about your situation and service request.</p>
</div>
</div>
</div>
<div class="w3-container w3-third" style="padding:0px; ">
<div class="div-plain quarter-padding" style="">
<div class="input-row">
<label class="form-field-text">Details</label><br><textarea name="Message" id="Message"
class="input-field" id="Message" cols="60" rows="6"></textarea>
</div>
<div class="input-row">
<p class="form-field-text">Supporting Files</p>
<div class="attachment-row">
<input type="file" class="input-field" name="attachment[]" accept=".pdf,.doc,.docx,.xlsx,.xls" />
</div>
<div onClick="addMoreAttachment();" class="icon-add-more-attachemnt" title="Add More Attachments"><img
src="icon-add-more-attachment.png" alt="Add More Attachments">
</div>
</div>
<div>
<input type="submit" name="send" class="btn-submit" value="Send Request" />
</div>
</div>
</div>
<div class="clearfix" style="clear:both"></div>
<div class="mail-sent-status">
<div class="status-message"> </div>
</div>
<div class="overlay"></div>
</form>
<script>
//form validation and submit
$("#mailForm").submit(function(e){
e.preventDefault();
});
$("#mailForm").validate({
rules: {
userName: {
required: true
},
Company: {
required: true
},
Phone: {
required: true
},
ModelNumber: {
required: true
},
SerialNumber: {
required: true
},
Message: {
required: true
},
userEmail: {
required: true,
email: true
}
},
submitHandler: function(form) {
var msgHolder = $('.mail-sent-status');
var url = $(form).attr('action') ;
var data = $(form).serialize();
var myForm = document.getElementById('mailForm');
var formData = new FormData(myForm);
$.ajax({
url: url,
type: 'post',
// data: data,
data: formData,
contentType: false,
dataType: 'json',
cache: false,
processData: false,
beforeSend:function () {
$('.overlay').fadeIn();
},
success: function(response) {
$('.overlay').fadeOut();
// console.log(response)
var result = response;
// var result = JSON.parse(response);
console.log(result)
if(result.status == false){
msgHolder.find('.status-message').removeClass('success').addClass('failed').html(result.message)
} else {
$(form).trigger("reset");
msgHolder.find('.status-message').removeClass('failed').addClass('success').html(result.message)
}
}
});
return false;
}
});
</script>
and
send_email_service_request.php
<?php
error_reporting(E_ALL);
ini_set('display_errors',1);
ini_set('error_reporting', E_ALL);
ini_set('display_startup_errors',1);
error_reporting(-1);
//script use from https://www.codexworld.com/php-contact-form-send-email-with-attachment-on-submit/
$sub = $_POST["subject"];
$userName = $_POST["userName"];
$company = $_POST["Company"];
$userEmail = $_POST["userEmail"];
$modelNumber = $_POST["ModelNumber"];
$serialNumber = $_POST["SerialNumber"];
$comment = $_POST["Message"];
$uploadedFileType = array();
$uploadedFileName = array();
// Upload attachment file
$uploadStatus = 1;
if(!empty($_FILES["attachment"]["name"])){
// File path config
// $targetDir = dirname(__FILE__)."/email-files/";
// $fileName = basename($_FILES["attachment"]["name"]);
// $targetFilePath = $targetDir . $fileName;
// $fileType = pathinfo($targetFilePath,PATHINFO_EXTENSION);
// // Allow certain file formats
// $allowTypes = array('pdf', 'doc', 'docx', 'xlsx', 'xls');
// if(in_array($fileType, $allowTypes)){
// // Upload file to the server
// if(move_uploaded_file($_FILES["attachment"]["tmp_name"], $targetFilePath)){
// $uploadedFile[] = $targetFilePath;
// } else {
// $uploadStatus = 0;
// $result['file'] = "Sorry, there was an error uploading your file.";
// }
// } else {
// $uploadStatus = 0;
// $result['file'] = 'Sorry, only PDF, DOC, Excel files are allowed to upload.';
// }
for($i=0; $i < count($_FILES['attachment']['name']); $i++){
$uploadedFileType[] = $_FILES['attachment']['type'][$i];
$uploadedFileName[] = $_FILES['attachment']['name'][$i];
}
}
$files = $uploadedFileName;
$to = "info#online-engineering.com";
// if($uploadStatus == 1){
// Recipient
// $to = "azizulh.ilbd#gmail.com";
// Subject
$subject = "ONLINE Engineering [".$sub."]";
// Message
$htmlContent = '
<html>
<head>
<title>Sender Information</title>
</head>
<body>
<table>
<tr>
<th style="text-align:left;width: 160px;">Name: </th>
<td style="text-align:left;">'. $userName .'</td>
</tr>
<tr>
<th style="text-align:left;width: 160px;">Email: </th>
<td style="text-align:left;">'.$userEmail.'</td>
</tr>
<tr>
<th style="text-align:left;width: 160px;">Company: </th>
<td style="text-align:left;">'.$company.'</td>
</tr>
<tr>
<th style="text-align:left;width: 160px;">Machine Model Number: </th>
<td style="text-align:left;">'.$modelNumber .'</td>
</tr>
<tr>
<th style="text-align:left;width: 160px;">Machine Serial Number: </th>
<td style="text-align:left;">'.$serialNumber.'</td>
</tr>
<tr>
<th style="text-align:left;width: 160px;" colspan="2">Details: </th>
</tr>
<tr>
<td style="text-align:left;" colspan="2">'.$comment.'</td>
</tr>
</table>
</body>
</html>
';
// Header for sender info
$headers = "From: $userName"." <".$userEmail.">";
if(!empty($files) && count($files) > 0){
// Boundary
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
// Headers for attachment
$headers .= "\nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . " boundary=\"{$mime_boundary}\"";
// Multipart boundary
$message = "--{$mime_boundary}\n" . "Content-Type: text/html; charset=\"UTF-8\"\n" .
"Content-Transfer-Encoding: 7bit\n\n" . $htmlContent . "\n\n";
// Preparing attachment
for($x=0;$x<count($files);$x++){
$file = #fopen($files[$x],"rb");
$data = #fread($file,filesize($files[$x]));
#fclose($file);
$data = chunk_split(base64_encode($data));
$message .= "Content-Type: {\"application/octet-stream\"};\n" . " name=\"$files[$x]\"\n" .
"Content-Disposition: attachment;\n" . " filename=\"$files[$x]\"\n" .
"Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";
$message .= "--{$mime_boundary}\n";
// $message .= "Content-Type: application/octet-stream; name=\"".$files[$x]."\"\n" .
// "Content-Description: ".$files[$x]."\n" .
// "Content-Disposition: attachment;\n" . " filename=\"".$files[$x]."\"; size=".filesize($files[$x]).";\n" .
// "Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";
$message .= "--{$mime_boundary}--";
}
// Send email
$mail = mail($to, $subject, $message, $headers);
} else {
// Set content-type header for sending HTML email
$headers .= "\r\n". "MIME-Version: 1.0";
$headers .= "\r\n". "Content-type:text/html;charset=UTF-8";
// Send email
$mail = mail($to, $subject, $htmlContent, $headers);
}
// }
if( $mail ){
$result['status'] = true;
$result['message'] = 'Your mail has been sent successfuly ! Thank you.';
//$result['error'] = $mail->ErrorInfo;
die(json_encode($result));
} else {
$result['status'] = false;
$result['message'] = 'Your mail has not been sent! There is an error. Please try again.';
//$result['error'] = $mail;
die(json_encode($result));
}
//die();
// echo "Mailer Error: " . $mail->ErrorInfo;
?>
Here is the live http://online-engineering.com/custom-machining.php

simple php captcha contact form

i am trying to create simple contact form with captcha in php. However it turns out implementing captcha is out of my league.
I found a simple answer on stackoverflow opn similar problem which pushed me 1 step closer to the end, but again i got stuck.
So i need a contact form that only check if text is entered and if correct captcha is answered, email is not mandatory.
</br>
<?php
$a=rand(2,9);
$b=rand(2,9);
$c=$a+$b;
if (isset($_POST['contact_text']) && isset($_POST['contact_email']) ) {
$contact_text = $_POST['contact_text'];
$contact_email = $_POST['contact_email'];
$recaptcha = $_POST['recaptcha'];
$info = 'Pranešimas apie korupciją: ';
$sender = 'Atsiuntė: ';
if (!empty($contact_text) && ($recaptcha == $c )) {
echo $recaptcha;
$to = 'muksinovas#gmail.com';
$subject = 'Korupcija';
$body = $sender."\n".$contact_email."\n".$info."\n".$contact_text;
$headers = 'From: '.$contact_email;
if (#mail($to,$subject, $body, $headers)) {
echo 'Jūsų pranešimas sėkmingai išsiustas. ';
} else {
} echo 'Įvyko klaida, bandykite dar karta.';
} else {
echo 'Neteisingai užpildyta forma.';
}
}
?>
<form action="contact1.php" method="post">
Pranešimas apie korupciją:<br><textarea name="contact_text" rows="6" cols="30" maxlength="1000" ></textarea><br><br> <!-- -->
Email (nebūtinas):<br><input type="text" name="contact_email" maxlength="30">
<?php echo $a."+".$b."="?><input type="number" name="recaptcha" maxlength="2" style="width:40px" />
<input type="submit" value="Siusti">
<br>
</form>
Now the problem is that I always get the message that details are incorrect. I tried to echo recaptcha just to see if $c is correct and it works. But for some reason not able to compare $recaptcha with $c or some other issue I am not sure.
The value of $c will be a completely different value when the user submits the contact form vs when your validation checks it. The value will change on every request because the script is re-interpreted.
You will have to save the value of $c on the initial page load, so that you can compare it afterwards in the next request. You can do that by storing it in $_SESSION.
You can write this
<?php
$min_number = 2;
$max_number = 9;
$random_number1 = mt_rand($min_number, $max_number);
$random_number2 = mt_rand($min_number, $max_number);
if (isset($_POST['contact_text']) && isset($_POST['contact_email']) ) {
$contact_text = $_POST['contact_text'];
$contact_email = $_POST['contact_email'];
$recaptcha = $_POST['recaptcha'];
$firstNumber = $_POST["firstNumber"];
$secondNumber = $_POST["secondNumber"];
$checkTotal = $firstNumber + $secondNumber;
$info = 'Pranešimas apie korupciją: ';
$sender = 'Atsiuntė: ';
if (!empty($contact_text) && ($recaptcha != $checkTotal )) {
echo $recaptcha;
$to = 'muksinovas#gmail.com';
$subject = 'Korupcija';
$body = $sender."\n".$contact_email."\n".$info."\n".$contact_text;
$headers = 'From: '.$contact_email;
if (#mail($to,$subject, $body, $headers)) {
echo 'Jūsų pranešimas sėkmingai išsiustas. ';
} else {
} echo 'Įvyko klaida, bandykite dar karta.';
} else {
echo 'Neteisingai užpildyta forma.';
}
}
?>
<form action="contact1.php" method="post">
Pranešimas apie korupciją:<br><textarea name="contact_text" rows="6" cols="30" maxlength="1000" ></textarea><br><br> <!-- -->
Email (nebūtinas):<br><input type="text" name="contact_email" maxlength="30">
<?php
echo $random_number1 . ' + ' . $random_number2 . ' = ';
?>
<input type="number" name="recaptcha" maxlength="2" style="width:40px" />
<input name="firstNumber" type="hidden" value="<?php echo $random_number1; ?>" />
<input name="secondNumber" type="hidden" value="<?php echo $random_number2; ?>" />
<input type="submit" value="Siusti">
<br>
</form>
This might solve your problem
you should to use session to solve your problem, i did little changes in your code, it should to work perfectly.
<?php
#session_start();
if (isset($_POST['contact_text']) && isset($_POST['contact_email']) ) {
$contact_text = $_POST['contact_text'];
$contact_email = $_POST['contact_email'];
$recaptcha = $_POST['recaptcha'];
$info = 'Pranešimas apie korupciją: ';
$sender = 'Atsiuntė: ';
if (!empty($contact_text) && ($recaptcha == $_SESSION["captcha"])) {
echo $recaptcha;
$to = 'muksinovas#gmail.com';
$subject = 'Korupcija';
$body = $sender."\n".$contact_email."\n".$info."\n".$contact_text;
$headers = 'From: '.$contact_email;
if (#mail($to,$subject, $body, $headers)) {
echo 'Jūsų pranešimas sėkmingai išsiustas. ';
} else {
} echo 'Įvyko klaida, bandykite dar karta.';
}else{
echo 'Neteisingai užpildyta forma.';
}
}else{
$a=rand(2,9);
$b=rand(2,9);
$c=$a+$b;
//setting captcha code in session
$_SESSION["captcha"] = $c;
?>
<form action="contact1.php" method="post">
Pranešimas apie korupciją:<br><textarea name="contact_text" rows="6" cols="30" maxlength="1000" ></textarea><br><br> <!-- -->
Email (nebūtinas):<br><input type="text" name="contact_email" maxlength="30">
<?php echo $a."+".$b."="?><input type="number" name="recaptcha" maxlength="2" style="width:40px" />
<input type="submit" value="Siusti">
<br>
</form>
<?php
}
?>

Uploading an image from contact form and send as email attachement

I am trying to add a new field in the contact us form field, but I am stumped on how to properly do this. I simply need to have the uploaded file be sent as an attachment of the contact us email. Thanks in advance Rahul
Here is my PHP code:
<?php
$submitted = FALSE;
if ($_POST['contact_form']) {
$submitted = TRUE; // The form has been submitted and everything is ok so far…
$name = htmlspecialchars($_POST['name'], ENT_QUOTES);
$email = htmlspecialchars($_POST['email'], ENT_QUOTES);
$country = htmlspecialchars($_POST['country'], ENT_QUOTES);
$message = htmlspecialchars($_POST['message'], ENT_QUOTES);
if ($name == "") {
// if the name is blank… give error notice.
echo "<p>Please enter your name.</p>";
$submitted = FALSE; // Set this to FALSE so that it the message is not sent.
}
if ($email == "") {
// if the email is blank… give error notice.
echo "<p>Please enter your e-mail address so that we can reply to you.</p>";
$submitted = FALSE; // Set this to FALSE so that it the message is not sent.
}
if ($country == "") {
// if the country is blank… give error notice.
echo "<p>Please enter your country.</p>";
$submitted = FALSE; // Set this to FALSE so that it the message is not sent.
}
if ($message == "") {
// if the message is blank… give error notice.
echo "<p>Please enter a question.</p>";
$submitted = FALSE; // Set this to FALSE so that it the message is not sent.
}
if ($_POST['email'] != "" && (!strstr($_POST['email'],"#") || !strstr($_POST['email'],".")))
{
// if the string does not contain "#" OR the string does not contain "." then…
// supply a different error notice.
echo "<p>Please enter a valid e-mail address.</p>";
$submitted = FALSE; // Set this to FALSE so that it the message is not sent.
}
$problemIn = '';
$ip = $_SERVER['REMOTE_ADDR'];
$url = (!empty($_SERVER['HTTPS']))
? "https://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI']
: "http://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
$to = "rahul#test.com"; // Set the target email address.
$header = "From: $email";
$attention = "Someone has sent you question from your webpage!";
$message = "Name: $name \n Country: $country \n Question: $message \n IP Address: $ip \n Link: $url \n";
if ($submitted == TRUE)
{
mail($to, $attention, $message, $header);
echo '<script type="text/javascript">alert("Thank you. Your question has been sent.");</script>';
}
}
?>
Here is my HTML code:
<form method="post" name="frmmail" id="frmmail" action="<?php echo $_SERVER['SCRIPT_NAME'] ?>" onSubmit="javascript: return validation();" eenctype="multipart/form-data">
<input name="name" id="txtname" value="" placeholder="Name" onfocus="if(this.value == 'Name')" class="usericon" />
<input name="email" id="txtmail" value="" placeholder="Email" onfocus="if(this.value == 'Email')" class="emailicon" />
<input name="country" id="txtcountry" value="" placeholder="Country" onfocus="if(this.value == 'Country')" style="margin:0" class="countryicon" />
<textarea name="message" id="txtmsg" placeholder="Your Comment/Question" onfocus="if(this.value == 'Your Question')" class="msgicon"></textarea>
<input type="file" name="file" class="file" />
<input type="submit" value="Submit" class="button" />
<input type="hidden" name="contact_form" value="submitted" />
</form>
Here is HTML Form
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Email Attachment Without Upload - Excellent Web World</title>
<style>
body{ font-family:Arial, Helvetica, sans-serif; font-size:13px;}
th{ background:#999999; text-align:right; vertical-align:top;}
input{ width:181px;}
</style>
</head>
<body>
<form action="emailSend.php" method="post" name="mainform" enctype="multipart/form-data">
<table width="500" border="0" cellpadding="5" cellspacing="5">
<tr>
<th>Your Name</th>
<td><input name="fieldFormName" type="text"></td>
</tr>
<tr>
<tr>
<th>Your Email</th>
<td><input name="fieldFormEmail" type="text"></td>
</tr>
<tr>
<th>To Email</th>
<td><input name="toEmail" type="text"></td>
</tr>
<tr>
<th>Subject</th>
<td><input name="fieldSubject" type="text" id="fieldSubject"></td>
</tr>
<tr>
<th>Comments</th>
<td><textarea name="fieldDescription" cols="20" rows="4" id="fieldDescription"></textarea></td>
</tr>
<tr>
<th>Attach Your File</th>
<td><input name="attachment" type="file"></td>
</tr>
<tr>
<td colspan="2" style="text-align:center;"><input type="submit" name="Submit" value="Send"><input type="reset" name="Reset" value="Reset"></td>
</tr>
</table>
</form>
PHP Code
<?php
$to = $_POST['toEmail'];
$fromEmail = $_POST['fieldFormEmail'];
$fromName = $_POST['fieldFormName'];
$subject = $_POST['fieldSubject'];
$message = $_POST['fieldDescription'];
/* GET File Variables */
$tmpName = $_FILES['attachment']['tmp_name'];
$fileType = $_FILES['attachment']['type'];
$fileName = $_FILES['attachment']['name'];
/* Start of headers */
$headers = "From: $fromName";
if (file($tmpName)) {
/* Reading file ('rb' = read binary) */
$file = fopen($tmpName,'rb');
$data = fread($file,filesize($tmpName));
fclose($file);
/* a boundary string */
$randomVal = md5(time());
$mimeBoundary = "==Multipart_Boundary_x{$randomVal}x";
/* Header for File Attachment */
$headers .= "\nMIME-Version: 1.0\n";
$headers .= "Content-Type: multipart/mixed;\n" ;
$headers .= " boundary=\"{$mimeBoundary}\"";
/* Multipart Boundary above message */
$message = "This is a multi-part message in MIME format.\n\n" .
"--{$mimeBoundary}\n" .
"Content-Type: text/plain; charset=\"iso-8859-1\"\n" .
"Content-Transfer-Encoding: 7bit\n\n" .
$message . "\n\n";
/* Encoding file data */
$data = chunk_split(base64_encode($data));
/* Adding attchment-file to message*/
$message .= "--{$mimeBoundary}\n" .
"Content-Type: {$fileType};\n" .
" name=\"{$fileName}\"\n" .
"Content-Transfer-Encoding: base64\n\n" .
$data . "\n\n" .
"--{$mimeBoundary}--\n";
}
$flgchk = mail ("$to", "$subject", "$message", "$headers");
if($flgchk){
echo "A email has been sent to: $to";
}
else{
echo "Error in Email sending";
}
?>

PHP Contact Form - Validation and

I'm new to php and have been trying to figure out how to properly validate email addresses and that data has been entered into the text boxes. I can't really find what I need and trying to follow the examples on php.net sends me into a circle. Any help would be greatly appreciated! Also, am I even heading in the right direction with this form? The form works, I get an email formatted the way I want to either of the email address in the dropdown box.
-UPDATE- I rewrote some of my script...can someone check it out, I'm having more problems now. It will send an email even if nothing is entered into the form and even if you do it will send whatever you put. Example "email" test#example is being allowed through.
<?php
//Sainitize function
function sanitizeString($value){
$value = strip_tags($value);
$value = trim($value);
$value = escapeshellcmd($value);
$value = htmlentities($value);
return $value;
}
$send = $_POST[send];
//Email validation - does not work by the way
if (filter_var($from, FILTER_VALIDATE_EMAIL)) {
$email_error = true;
$error_message[] = "Please use a valid email format: name#domain.com";
}
if($send == 1){$email_sent = true; $step_1 = "complete";}
else{$email_sent = false; $step_1 = "complete";}
if($email_sent === true) {
$from = sanitizeString($_POST['from']);
$to = sanitizeString($_POST['to']);
$name = sanitizeString($_POST['name']);
$title = sanitizeString($_POST['title']);
$company = sanitizeString($_POST['company']);
$phone = sanitizeString($_POST['phone']);
$subject = sanitizeString($_POST['subject']);
$message = sanitizeString($_POST['message']);
// define variables and initialize with empty values
$nameErr = $addressErr = $emailErr = $messageErr = $phoneErr = "";
$name = $address = $email = $message = $phone = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Please enter your name.";
}
else {
$name = $_POST["name"];
}
if (empty($_POST["email"])) {
$emailErr = "Please enter your email.";
}
else {
$email = $_POST["email"];
}
if (empty($_POST["phone"])) {
$phoneErr = "Please enter a phone number.";
}
else {
$phone = $_POST["phone"];
}
if (empty($_POST["message"])) {
$messageErr = "Cannot leave message box blank.";
}
else {
$message = $_POST["message"];
}
}
//select the correct to address
switch ($to) {
case "1":
$to = "contact1#example.com";
break;
case "2":
$to = "contact2#example.com";
break;
default:
$to = "contact1#example.com";
break;}
if($message_error !== true && $email_error !== true){
$email_headers = "From:".$from."\nMIME-Version: 1.0 \nContent-type: text/html; charset=iso-8859-1";
$message_send = "<h3>".$name."<br>".$title."<br>".$company."<br>".$phone."<br>".$from."</h3><hr><h4>".$subject."</h4>".$message;
if (mail($to, $subject, $message_send, $email_headers)) {$error_message = "Thank you, your email is on the way!";}
else {$error_message = "There seems to be a problem!";}}
}
?>
<body>
<form action="<?php ($_SERVER["PHP_SELF"]);?>" method="post">
<table style="border-collapse:collapse; border-spacing:0" >
<tr>
<td>Name:</td>
<td><input name="name" placeholder="Name*" type="text" class="text"/>
<span class="error"><?php echo $nameErr;?></span></td>
</tr>
<tr>
<td>Title:</td>
<td><input type="text" placeholder="Title" name="title" size="50"/></td>
</tr>
<tr>
<td>Company:</td>
<td><input type="text" placeholder="Company" name="company" size="50" /></td>
</tr>
<tr>
<td>Phone:</td>
<td>
<input name="phone" placeholder="Phone*" type="tel" size="10" maxlength="10" value="<?php echo htmlspecialchars($phone);?>"/>
<span class="style1">Example: 1234567890</span> <span class="error" style="color:#990000"><?php echo $phoneErr;?></span></td>
</tr>
<tr>
<td>Email:</td>
<td><input name="from" placeholder="Email*" type="email" class="text" value="<?php echo htmlspecialchars($email);?>">
<span class="error"><?php echo $emailErr;?></span></td>
</tr>
<tr>
<td>To:</td>
<td><select name="to" size="1">
<option value="1">Contact 1</option>
<option value="2">Contact 2</option>
</select></td>
</tr>
<tr>
<td>Subject:</td>
<td><input type="text" name="subject" placeholder="Subject" size="50" /></td>
</tr>
<tr>
<td valign="top">Detail:</td>
<td colspan="2"><textarea cols="50" rows="4" name="message" placeholder="Type your message here."></textarea></td>
</tr>
<tr>
<td colspan="2" style="text-align:center;"><input type="hidden" name="send" value="1" /><input type="submit" value="Send" name="email_1" /></td>
</tr>
</table >
</form>
For e-mail validation you can use filter_var function with FILTER_VALIDATE_EMAIL filter property. Here is nice article about input validation. Try this from php manual:
var_dump(filter_var('bob#example.com', FILTER_VALIDATE_EMAIL));
You can simplify your code, it's a bit messy. switch e-mail addresses is not very good practice. You can add values to form like this:
<select name="to" size="1">
<option value="contact1#example.com">Contact1</option>
<option value="contact2#example.com">Contact2</option>
</select>
You are also using deprecated function mysql_escape_string. ltrim and rtrim can be replaced with trim function.
UPDATE
There is still lot of mistakes in your code. Do you have displayed error reportings? Email switching is definitely not good solution for your problem. Take a look on the refactored code, it should work for you:
<?php
//Sainitize function
function sanitizeString($value)
{
$value = strip_tags($value);
$value = trim($value);
$value = escapeshellcmd($value);
$value = htmlentities($value);
return $value;
}
$errorMessage = array();
$receivers = array(
1 => 'contact1#example.com',
2 => 'contact2#example.com'
);
if(isset($_POST['form']))
{
$formData = $_POST['form'];
if (filter_var($formData['from'], FILTER_VALIDATE_EMAIL)) {
$from = sanitizeString($formData['from']);
}
else
{
$errorMessage[] = "Please use a valid email format: name#domain.com";
}
if(array_key_exists($formData['to'], $receivers))
{
$to = $receivers[$formData['to']];
}
else
{
$to = 'default#example.com';
}
if(strlen($formData['name']) > 0)
{
$name = sanitizeString($formData['name']);
}
else
{
$errorMessage[] = "Please enter your name.";
}
if(strlen($formData['title']) > 0)
{
$title = sanitizeString($formData['title']);
}
else
{
$title = '';
}
if(strlen($formData['company']) > 0)
{
$company = sanitizeString($formData['company']);
}
else
{
$company = '';
}
if(strlen($formData['phone']) > 0)
{
$phone = sanitizeString($formData['phone']);
}
else
{
$errorMessage[] = "Please enter a phone number.";
}
if(strlen($formData['subject']) > 0)
{
$subject = sanitizeString($formData['subject']);
}
else
{
$subject = '';
}
if(strlen($formData['message']) > 0)
{
$message = sanitizeString($formData['message']);
}
else
{
$errorMessage[] = 'Cannot leave message box blank.';
}
if (empty($errorMessage) && $formData['spam'] == 9)
{
$email_headers = "From:" . $from . "\nMIME-Version: 1.0 \nContent-type: text/html; charset=iso-8859-1";
$message_send = "<h3>" . $name . "<br>" . $title . "<br>" . $company . "<br>" . $phone . "<br>" . $from . "</h3><hr><h4>" . $subject . "</h4>" . $message;
if (mail($to, $subject, $message_send, $email_headers))
{
$errorMessage[] = 'Thank you, your email is on the way!';
}
else
{
$errorMessage[] = 'There seems to be a problem!';
}
}
}
?>
<body>
<?php if(!empty($errorMessage)): ?>
<div style="border: 2px solid red">
<ul>
<?php foreach ($errorMessage as $error): ?>
<li><?php echo $error; ?></li>
<?php endforeach; ?>
</ul>
</div>
<?php endif; ?>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<table style="border-collapse:collapse; border-spacing:0">
<tr>
<td>Name:</td>
<td>
<input name="form[name]" placeholder="Name*" type="text" class="text" value="<?php echo isset($name) ? $name : ''; ?>"/>
</td>
</tr>
<tr>
<td>Title:</td>
<td>
<input type="text" placeholder="Title" name="form[title]" size="50" value="<?php echo isset($title) ? $title : ''; ?>"/>
</td>
</tr>
<tr>
<td>Company:</td>
<td>
<input type="text" placeholder="Company" name="form[company]" size="50" value="<?php echo isset($company) ? $company : ''; ?>"/>
</td>
</tr>
<tr>
<td>Phone:</td>
<td>
<input name="form[phone]" placeholder="Phone*" type="tel" size="10" maxlength="10" value="<?php echo isset($phone) ? $phone : ''; ?>"/>
<span class="style1">Example: 1234567890</span>
</td>
</tr>
<tr>
<td>Email:</td>
<td>
<input name="form[from]" placeholder="Email*" type="email" class="text" value="<?php echo isset($from) ? $from : ''; ?>">
</td>
</tr>
<tr>
<td>To:</td>
<td>
<select name="form[to]" size="1">
<option value="1">Contact 1</option>
<option value="2">Contact 2</option>
</select>
</td>
</tr>
<tr>
<td>Subject:</td>
<td>
<input type="text" name="form[subject]" placeholder="Subject" size="50" value="<?php echo isset($subject) ? $subject : ''; ?>"/>
</td>
</tr>
<tr>
<td valign="top">Detail:</td>
<td colspan="2">
<textarea cols="50" rows="4" name="form[message]" placeholder="Type your message here."><?php echo isset($message) ? $message : ''; ?></textarea>
</td>
</tr>
<tr>
<td></td>
<td>
3x3 = <input type="text" value="" name="form[spam]"/>
<input type="submit" value="Send" />
</td>
</tr>
</table>
</form>
I found this on php.net.. Does it work?
if (filter_var($from, FILTER_VALIDATE_EMAIL)) {
$email_error = true;
$error_message[] = "Please use a valid email format: name#domain.com";
}
The Filter var does work. Try the following piece of code.
<?php
$emailError = array();
if(isset($_POST["send"])){
$from = $_POST["from"];
if (!filter_var($from, FILTER_VALIDATE_EMAIL)) {
$emailError[] = "Please use a valid email format: name#domain.com\n\r";
}
else {
echo $from . " is a valid email.\n\r";
}
if ($emailError){
foreach ($emailError as $key){
echo $key;
}
}
} else {
?>
<form action="<?php ($_SERVER["PHP_SELF"]);?>" method="post">
<table>
<tr>
<td>Email:</td>
<td>
<input name="from" placeholder="Email*" type="email" class="text" value="">
</td>
</tr>
</table>
<input type="submit" value="Send" name="send" />
</form>
<?php
}
?>

PHP contact form submitting but not receiving email

I realise this question has been asked numerous times before but everyone's code is obviously different and I am quite new to php so just looking to see if someone can give me some help.
I have created a basic contact form for a site but for some reason the information is not being sent to my email address although I believe that the form is submitted?
my PHP code is:
<?php
session_start();
//$to_mail = "architects#palavin.com,t.lavin#palavin.com,12yorkcourt#gmail.com";
$to_mail = "danny#enhance.ie";
//$cc="paul#enhance.ie";
$mail_sent = 0;
if(isset($_POST['submit'])){
//echo "the form was submitted";
$error= array();
$name = trim(strip_tags($_POST['name']));
if($name == "")
$error['name'] = 1;
$email = trim(strip_tags($_POST['email']));
if($email == "")
$error['email'] = 1;
$phone = trim(strip_tags($_POST['phone']));
$address = trim(strip_tags($_POST['address']));
$description = trim(strip_tags($_POST['description']));
$str = trim(strip_tags($_POST['secu']));
if ( isset($_SESSION['code_']) && $_SESSION['code_'] == strtoupper($str)){} else {$error['secu'] = 1;}
if(empty($error)){
$headers = 'From: "Euro Insulation" <no-reply#euroinsulations.ie>'."\r\n";
//$headers .= 'CC: "'.$cc.'" <'.$cc.'>'."\r\n";
$headers .= 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=utf-8' . "";
$subject = "New contact message";
$message = "New Contact message, received from: <br /> \n ";
$message .= "<b>Name</b> ".$name."<br /> \n";
$message .= "<b>Email</b> ".$email."<br /> \n";
$message .= "<b>Phone</b> ".$phone."<br /> \n";
$message .= "<b>Address</b> ".$address."<br /> \n";
$message .= "<b>Description</b> ".$description."<br /> \n";
if(#mail($to_mail,$subject,$message,$headers ))
{
echo "mail sent";
$mail_sent = 1;
}
else echo "mail not sent";
}
}
?>
my html form looks like this:
<table width="100%" border="0" cellspacing="0" cellpadding="10">
<tr>
<td width="65%" valign="top"><p class="header"><br>
Contact US <br>
</p>
<?php if($mail_sent==1){
print "Thank you for your message.";
} else { ?>
<form class="email_sub" method="post" >
<table width="77%" border="0" align="center" cellpadding="2" cellspacing="0">
<tr>
<td><label for="name" class="formtext" <?php if($error['name']==1) echo "style='color:red;'" ?> >Name:</label></td>
<td><input type="text" name="name" id="text" <?php if($name) echo "value='".$name."'" ?> /></td>
</tr>
<tr>
<td><label for="phone" class="formtext">Number:</label></td>
<td><input type="text" name="phone" id="phone"/><tr>
<br />
<tr>
<td><label for="email" class="textarea" <?php if($error['email']==1) echo "style='color:red;'" ?>>Email:</label></td>
<td><input type="text" name="email" id="email" <?php if($email) echo "value='".$email."'" ?> /></td>
</tr>
<tr>
<td><br /></td>
</tr>
<tr><td><label for="address" class="textarea">Address/Location of project:</label></td>
<td><textarea rows="3" cols="20" name="address" id="address" style="width: 400px;"><?php if($address!="") echo $address ?></textarea></td>
</tr>
<tr>
<td><br /></td>
</tr>
<br />
<tr>
<td><label for="description" class="fixedwidth">Enquiry</label></td>
<td><textarea rows="3" cols="20" name="description" id="description" style="width: 400px;"><?php if($description!="") echo $description; ?></textarea></td>
<tr>
<td><br /></td>
</tr>
<!-- form -->
<tr>
<td><label> </label></td>
<td><input type="submit" value="Submit" name="submit" /></td>
</tr>
</table>
</form>
<?php } ?>
Am i missing something obvious here?? Any help will really be appreciated thanks!
You have used sessions which is not required here, you can also use flag variable instead of arrays in this simple form, use this updated code.
<?php
//$to_mail = "architects#palavin.com,t.lavin#palavin.com,12yorkcourt#gmail.com";
$to_mail = "danny#enhance.ie";
//$cc="paul#enhance.ie";
$mail_sent = 0;
if(isset($_POST['submit'])){
//echo "the form was submitted";
$name = trim(strip_tags($_POST['name']));
if($name == "")
$error = true;
$email = trim(strip_tags($_POST['email']));
if($email == "")
$error = true;
$phone = trim(strip_tags($_POST['phone']));
$address = trim(strip_tags($_POST['address']));
$description = trim(strip_tags($_POST['description']));
if($error != true){
$headers = 'From: "Euro Insulation" <no-reply#euroinsulations.ie>'."\r\n";
//$headers .= 'CC: "'.$cc.'" <'.$cc.'>'."\r\n";
$headers .= 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=utf-8' . "";
$subject = "New contact message";
$message = "New Contact message, received from: <br /> \n ";
$message .= "<b>Name</b> ".$name."<br /> \n";
$message .= "<b>Email</b> ".$email."<br /> \n";
$message .= "<b>Phone</b> ".$phone."<br /> \n";
$message .= "<b>Address</b> ".$address."<br /> \n";
$message .= "<b>Description</b> ".$description."<br /> \n";
if(#mail($to_mail,$subject,$message,$headers))
{
echo "mail sent";
$mail_sent = 1;
}
else echo "mail not sent";
} else {
echo 'validation error';
}
}
?>
You have also missed out the else statement for your form validation test so no errors getting displayed when you submit form.
Remove the at sign from mail function and see what errors your get. #mail suppresses errors from being displayed.
Comment out the following line: if ( isset($SESSION['code']) && $SESSION['code'] == strtoupper($str)){} else {$error['secu'] = 1;}
You should be able to reach the mail function.

Categories