PHP attachment form after submitting getting blank page - php

after submitting my form am getting the mail but its going to white black screen with message of message send.
I try to reload the page after the submit the form but getting error.
<?php
if ($_SERVER['REQUEST_METHOD'] == "POST") {
$to = "name#gmail.com";
$subject = "E-mail with attachment";
$from = stripslashes($_POST['fromname']) . "<" . stripslashes($_POST['fromemail']) . ">" . "<" . stripslashes($_POST['designation']) . ">";
// generate a random string to be used as the boundary marker
$mime_boundary = "==Multipart_Boundary_x" . md5(mt_rand()) . "x";
// now we'll build the message headers
$headers = "From: $from\r\n" .
"MIME-Version: 1.0\r\n" .
"Content-Type: multipart/mixed;\r\n" .
" boundary=\"{$mime_boundary}\"";
$message = "Canditade Resume";
// when we use it
$message = "This is a multi-part message in MIME format.\n\n" .
"--{$mime_boundary}\n" .
"Content-Type: text/plain; charset=\"iso-8859-1\"\n" .
"Content-Transfer-Encoding: 7bit\n\n" .
$message . "\n\n";
// iterating each File type
print_r($_FILES);
foreach ($_FILES as $userfile) {
$tmp_name = $userfile['tmp_name'];
$type = $userfile['type'];
$name = $userfile['name'];
$size = $userfile['size'];
if (file_exists($tmp_name)) {
if (is_uploaded_file($tmp_name)) {
$file = fopen($tmp_name, 'rb');
$data = fread($file, filesize($tmp_name));
fclose($file);
$data = chunk_split(base64_encode($data));
}
$message .= "--{$mime_boundary}\n" .
"Content-Type: {$type};\n" .
" name=\"{$name}\"\n" .
"Content-Disposition: attachment;\n" .
" filename=\"{$tmp_name}\"\n" .
"Content-Transfer-Encoding: base64\n\n" .
$data . "\n\n";
}
}
// here's our closing mime boundary that indicates the last of the message
$message.="--{$mime_boundary}--\n";
// now we just send the message
if (#mail($to, $subject, $message, $headers))
echo "Message Sent";
else
echo "Failed to send";
} else {
?>
<form action="index.php" method="post" enctype="multipart/form-data" name="form1">
<label>Name</label>
<input type="text" name="fromname" class="input-block-level" style="width: 100%" required placeholder="Your First Name">
<label>Email Address</label>
<input type="text" style="width: 100%" class="input-block-level" required placeholder="Your email address" name="fromemail">
<label>Designation</label>
<input type="text" style="width: 100%" class="input-block-level" name="designation" required placeholder="Designation">
<label>Upload Your CV</label>
<input type="file" class="input-block-level" required placeholder="Upload Your CV" name="file1">
</div>
<input type="submit" name="Submit" value="Submit" class="btn btn-primary btn-large pull-left" onclick="javascript: form.action='index.php';">
</form>
<?php } ?>
please help me

if (#mail($to, $subject, $message, $headers))
//echo "Message Sent";
header('location:email-success.php');
else
//echo "Failed to send";
header('location:email-error.php');
}

Give page name in header location to which you want to redirect it.
Change
if (#mail($to, $subject, $message, $headers))
echo "Message Sent";
else
echo "Failed to send";
} else {
To
if (#mail($to, $subject, $message, $headers))
header("location:yourpage.php?message=Message Sent");
else
header("location:yourpage.php?message=Failed to send");
} else {
yourpage.php
<?php
if(isset($_GET['message'])){
echo $_GET['message'];
}
.
.
?>

Your coding is a little messed. Here's the adjustments I made:
I also commented out the print_r($_FILES) as this will display the array of what has been passed through which you do not want to display when a user presses submit.
So I renamed the $_POST and made it an isset:
<?php
if (isset($_POST['send'])) {
$to = "name#gmail.com";
$subject = "E-mail with attachment";
$from = stripslashes($_POST['fromname']) . "<" . stripslashes($_POST['fromemail']) . ">" . "<" . stripslashes($_POST['designation']) . ">";
// generate a random string to be used as the boundary marker
$mime_boundary = "==Multipart_Boundary_x" . md5(mt_rand()) . "x";
// now we'll build the message headers
$headers = "From: $from\r\n" .
"MIME-Version: 1.0\r\n" .
"Content-Type: multipart/mixed;\r\n" .
" boundary=\"{$mime_boundary}\"";
$message = "Canditade Resume";
// when we use it
$message = "This is a multi-part message in MIME format.\n\n" .
"--{$mime_boundary}\n" .
"Content-Type: text/plain; charset=\"iso-8859-1\"\n" .
"Content-Transfer-Encoding: 7bit\n\n" .
$message . "\n\n";
// iterating each File type
//print_r($_FILES);
foreach ($_FILES as $userfile) {
$tmp_name = $userfile['tmp_name'];
$type = $userfile['type'];
$name = $userfile['name'];
$size = $userfile['size'];
if (file_exists($tmp_name)) {
if (is_uploaded_file($tmp_name)) {
$file = fopen($tmp_name, 'rb');
$data = fread($file, filesize($tmp_name));
fclose($file);
$data = chunk_split(base64_encode($data));
}
$message .= "--{$mime_boundary}\n" .
"Content-Type: {$type};\n" .
" name=\"{$name}\"\n" .
"Content-Disposition: attachment;\n" .
" filename=\"{$tmp_name}\"\n" .
"Content-Transfer-Encoding: base64\n\n" .
$data . "\n\n";
}
}
// here's our closing mime boundary that indicates the last of the message
$message .= "--{$mime_boundary}--\n";
// now we just send the message
if (#mail($to, $subject, $message, $headers)) {
echo "Message Sent";
} else {
echo "Failed to send";
}
}
?>
Not sure why you wrapped the PHP around the html side but that would be why you wasn't being taken back to the form side and just a blank page.
<form action="" method="post" enctype="multipart/form-data" name="form1">
<label>Name</label>
<input type="text" name="fromname" class="input-block-level" style="width: 100%" required placeholder="Your First Name">
<label>Email Address</label>
<input type="text" style="width: 100%" class="input-block-level" required placeholder="Your email address" name="fromemail">
<label>Designation</label>
<input type="text" style="width: 100%" class="input-block-level" name="designation" required placeholder="Designation">
<label>Upload Your CV</label>
<input type="file" class="input-block-level" required placeholder="Upload Your CV" name="file1">
</div>
<input type="submit" name="send" value="Submit" class="btn btn-primary btn-large pull-left" onclick="javascript: form.action='index.php';">
</form>
I have tested this code and it redirects back to the form with the "Message sent" above the form (as you'd see on any contact form).

Related

My contact form worked fine, until I added attachment option. Messages no longer get sent. Any idea how I could validate the attachment field?

I have made a contact form with the following fields: Name, Email, Message. It all worked fine - messages were sent to my email - until I added the attachments option to the form.
I've tried validating the attachment fields by searching up tutorials, but nothing seems to work. I guess I'm just not sure how to implement it to my already existing code.. Any help here?
Here is the form:
<?php include 'contact-form.php'; ?>
<form id="contact" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="multipart/form-data">
<h3>Contact Us</h3>
<fieldset>
<input placeholder="Nimi" type="text" tabindex="1" name="thename" value="<?= $thename ?>" autofocus>
<div class="error"><span><?= $name_error ?></span></div>
</fieldset>
<fieldset>
<input placeholder="Email" type="text" tabindex="2" name="email" value="<?= $email ?>">
<div class="error"><span><?= $email_error ?></span></div>
</fieldset>
<fieldset>
<textarea placeholder="Sisesta sõnum siia.." type="text" tabindex="3" name="message"></textarea>
<div class="error"><span><?= $message_error ?></span></div>
</fieldset>
<fieldset>
<label for="attachment1">File:</label> <input type="file" id="attachment1" name="attachment[]" size="35">
<label for="attachment2">File:</label> <input type="file" id="attachment2" name="attachment[]" size="35">
<div class="error"><span><?= $attachment_error ?></span></div>
</fieldset>
<fieldset>
<button name="submit" type="submit" id="contact-submit" data-submit="...Saatmine">Saada</button>
</fieldset>
<div class="success"><?= $success; ?></div>
<div class="error"><?= $error; ?></div>
</form>
Here is PHP validation code contact-form.php:
<?php
$name_error = $email_error = $message_error = $attachment_error = "";
$thename = $email = $message = $success = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["thename"])) {
$name_error = "Palun sisesta nimi";
} else {
$thename = test_input($_POST["thename"]);
// check if name only contains letters, whitespace and hyphen
if (!preg_match("/^[a-zA-Z -]*$/",$thename)) {
$name_error = "Sisestada saab ainult tähti, tühikuid ja sidekriipse";
}
}
if (empty($_POST["email"])) {
$email_error = "Palun sisesta email";
} else {
$email = test_input($_POST["email"]);
// email validation
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$email_error = "Sisesta email korrektselt";
}
}
if (empty($_POST["message"])) {
$message_error = "Palun sisesta sõnum";
} else {
$message = test_input($_POST["message"]);
}
if (empty($_FILES["attachment"])) {
$attachment_error = "Palun sisesta enda eluloo fail";
}
if ($name_error == '' and $email_error == '' and $message_error == '' ){
$message_body = '';
unset($_POST['submit']);
foreach ($_POST as $key => $value){
$message_body .= "$key: $value\n";
}
$to = 'myemail#gmail.com';
$subject = 'Eesti Elulood';
$message = "Sulle saadeti kiri Rannu koguduse kodulehelt.\n\nSaatja nimi: $thename\n\nSaatja email: $email\n\nSõnum: $message";
// create email headers
$headers = 'From: '.$email."\r\n".
'Reply-To: '.$email."\r\n" .
'X-Mailer: PHP/' . phpversion();
if (isset($_FILES['attachment']['name'])) {
$semi_rand = md5(uniqid(time()));
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
$headers = "From: " . '=?UTF-8?B?' . base64_encode($thename) . '?=' . "
<$email>" . PHP_EOL;
$headers .= "Reply-To: " . '=?UTF-8?B?' . base64_encode($thename) . '?=' .
" <$email>" . PHP_EOL;
$headers .= "Return-Path: $email" . PHP_EOL;
$headers .= "MIME-Version: 1.0" . PHP_EOL;
$headers .= "Content-Type: multipart/mixed;" . PHP_EOL;
$headers .= " Boundary=\"{$mime_boundary}\"";
$datamsg = "This is a multi-part message in MIME format." . PHP_EOL .
PHP_EOL;
$datamsg .= "--{$mime_boundary}" . PHP_EOL;
$datamsg .= "Content-Type: text/plain; Charset=\"UTF-8\"" . PHP_EOL;
$datamsg .= "Content-Transfer-Encoding: 8bit" . PHP_EOL . PHP_EOL;
$datamsg .= $message . PHP_EOL . PHP_EOL;
for ($index = 0; $index < count($_FILES['attachment']['name']); $index++)
{
if ($_FILES['attachment']['name'][$index] != "") {
$file_name = $_FILES['attachment']['name'][$index];
$data_file =
chunk_split(base64_encode(file_get_contents($_FILES['attachment']
['tmp_name'][$index])));
$datamsg .= "--{$mime_boundary}" . PHP_EOL;
$datamsg .= "Content-Type: application/octet-stream; Name=\"
{$file_name}\"" . PHP_EOL;
$datamsg .= "Content-Disposition: attachment; Filename=\"{$file_name}\"" . PHP_EOL;
$datamsg .= "Content-Transfer-Encoding: base64" . PHP_EOL . PHP_EOL .
$data_file . PHP_EOL . PHP_EOL;
}
}
$datamsg .= "--{$mime_boundary}--";
}
if (#mail($to, '=?UTF-8?B?' . base64_encode($subject) . '?=',
$datamsg, $headers, "-f$email")){
$success = "Thankyou, message sent!.";
} else {
$error = "Sorry but the email could not be sent. Please try again!";
}
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
After hitting the submit button, It just takes me to the index.php page..
Any help is appreciated!
1) You have no mail attachments code into your php code except for the html markup, so you cannot send your mail attachments.
2) You have to encode the attachments using chunk_split(base64_encode()) and then you have to import them into your message part using the correct way.
3) You forgot to enter the correct headers, that's the other reason why you can't send your mails.
4) You have to consider that if you use GMail there may be a limit to the type of file you can send and so read this: https://support.google.com/mail/answer/6590?hl=en
5) I suggest you to use the long php tag instead the short tag:
Instead of writing <?= $_SERVER['PHP_SELF']; ?>, write <?php echo $_SERVER['PHP_SELF']; ?>
6) You have a serious error into your php and this is the reason why pressing submit you are in the home instead of your contact form:
<?= $SERVER['PHP_SELF']; ?> is wrong!
<?= $_SERVER['PHP_SELF']; ?> is correct!
See you point 5)
Here is an example of correct html markup for attachments:
<label for="attachment1">File:</label> <input type="file" id="attachment1" name="attachment[]" size="35">
<label for="attachment2">File:</label> <input type="file" id="attachment2" name="attachment[]" size="35">
<label for="attachment3">File:</label> <input type="file" id="attachment3" name="attachment[]" size="35">
Here is an example of correct php mail code for attachments:
if (isset($_FILES['attachment']['name'])) {
$semi_rand = md5(uniqid(time()));
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
$headers = "From: " . '=?UTF-8?B?' . base64_encode($sender_name) . '?=' . " <$from_email>" . PHP_EOL;
$headers .= "Reply-To: " . '=?UTF-8?B?' . base64_encode($sender_name) . '?=' . " <$from_email>" . PHP_EOL;
$headers .= "Return-Path: $from_email" . PHP_EOL;
$headers .= "MIME-Version: 1.0" . PHP_EOL;
$headers .= "Content-Type: multipart/mixed;" . PHP_EOL;
$headers .= " Boundary=\"{$mime_boundary}\"";
$datamsg = "This is a multi-part message in MIME format." . PHP_EOL . PHP_EOL;
$datamsg .= "--{$mime_boundary}" . PHP_EOL;
$datamsg .= "Content-Type: text/plain; Charset=\"UTF-8\"" . PHP_EOL;
$datamsg .= "Content-Transfer-Encoding: 8bit" . PHP_EOL . PHP_EOL;
$datamsg .= $message . PHP_EOL . PHP_EOL;
for ($index = 0; $index < count($_FILES['attachment']['name']); $index++) {
if ($_FILES['attachment']['name'][$index] != "") {
$file_name = $_FILES['attachment']['name'][$index];
$data_file = chunk_split(base64_encode(file_get_contents($_FILES['attachment']['tmp_name'][$index])));
$datamsg .= "--{$mime_boundary}" . PHP_EOL;
$datamsg .= "Content-Type: application/octet-stream; Name=\"{$file_name}\"" . PHP_EOL;
$datamsg .= "Content-Disposition: attachment; Filename=\"{$file_name}\"" . PHP_EOL;
$datamsg .= "Content-Transfer-Encoding: base64" . PHP_EOL . PHP_EOL . $data_file . PHP_EOL . PHP_EOL;
}
}
$datamsg .= "--{$mime_boundary}--";
}
if (#mail($recipient_email, '=?UTF-8?B?' . base64_encode($subject) . '?=', $datamsg, $headers, "-f$from_email")) {
exit("Files Sent Successfully");
} else {
exit("Sorry but the email could not be sent. Please go back and try again!");
}
Where $sender_name is the name of sender, $from_email is the email of sender, $recipient_email is the recipient of your email.
You can take an example from my code and integrate it into your project, I wrote only the essential parts concerning the sending of attachments.
I hope this helps.

Email attachment using php, file can't open in email

This is my code, in this case, the code works perfectly and I got the attachment in the mail but the attached file can't be opened. Then I downloaded the file and tried to open it, it shows an error "either not a supported file type or file has been damaged(For example, it was send as an email attachment and wasn't correctly decoded)"
<form action="#" method="POST" enctype="multipart/form-data" >
<input type="file" name="csv_file[]" />
<br/>
<input type="file" name="csv_file[]" />
<br/>
<input type="file" name="csv_file[]" />
<br/>
<input type="submit" name="upload" value="Upload" />
<br/>
</form>
<?php
if($_POST) {
for($i=0; $i < count($_FILES['csv_file']['name']); $i++){
$ftype[] = $_FILES['csv_file']['type'][$i];
$fname[] = $_FILES['csv_file']['name'][$i];
}
// array with filenames to be sent as attachment
$files = $fname;
// email fields: to, from, subject, and so on
$to = "example#gmail.com";
$from = "example#gmail.com";
$subject ="My subject";
$message = "My message1";
$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 = "This is a multi-part message in MIME format.\n\n" . "--{$mime_boundary}\n" . "Content-Type: text/plain; charset=\"iso-8859-1\"\n" . "Content-Transfer-Encoding: 7bit\n\n" . $message . "\n\n";
$message .= "--{$mime_boundary}\n";
// preparing attachments
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";
}
// send
$ok = #mail($to, $subject, $message, $headers);
if ($ok) {
echo "<p>mail sent to $to!</p>";
} else {
echo "<p>mail could not be sent!</p>";
}
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>E-mail with Attachment</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>
<body>
<?php
if ($_SERVER['REQUEST_METHOD']=="POST"){
// we'll begin by assigning the To address and message subject
$to="example#gmail.com";
$subject="E-mail with attachment";
// get the sender's name and email address
// we'll just plug them a variable to be used later
$from = stripslashes($_POST['fromname'])."<".stripslashes($_POST['fromemail']).">";
// generate a random string to be used as the boundary marker
$mime_boundary="==Multipart_Boundary_x".md5(mt_rand())."x";
// now we'll build the message headers
$headers = "From: $from\r\n" .
"MIME-Version: 1.0\r\n" .
"Content-Type: multipart/mixed;\r\n" .
" boundary=\"{$mime_boundary}\"";
$message="This is an example";
$message .= "Name:".$_POST["fromname"]."Message Posted:".$_POST["modlist"];
$message = "This is a multi-part message in MIME format.\n\n" .
"--{$mime_boundary}\n" .
"Content-Type: text/plain; charset=\"iso-8859-1\"\n" .
"Content-Transfer-Encoding: 7bit\n\n" .
$message . "\n\n";
// now we'll process our uploaded files
foreach($_FILES as $userfile){
// store the file information to variables for easier access
$tmp_name = $userfile['tmp_name'];
$type = $userfile['type'];
$name = $userfile['name'];
$size = $userfile['size'];
// if the upload succeded, the file will exist
if (file_exists($tmp_name)){
// check to make sure that it is an uploaded file and not a system file
if(is_uploaded_file($tmp_name)){
// open the file for a binary read
$file = fopen($tmp_name,'rb');
// read the file content into a variable
$data = fread($file,filesize($tmp_name));
// close the file
fclose($file);
// now we encode it and split it into acceptable length lines
$data = chunk_split(base64_encode($data));
}
// now we'll insert a boundary to indicate we're starting the attachment
// we have to specify the content type, file name, and disposition as
// an attachment, then add the file content.
// NOTE: we don't set another boundary to indicate that the end of the
// file has been reached here. we only want one boundary between each file
// we'll add the final one after the loop finishes.
$message .= "--{$mime_boundary}\n" .
"Content-Type: {$type};\n" .
" name=\"{$name}\"\n" .
"Content-Disposition: attachment;\n" .
" filename=\"{$fileatt_name}\"\n" .
"Content-Transfer-Encoding: base64\n\n" .
$data . "\n\n";
}
}
// here's our closing mime boundary that indicates the last of the message
$message.="--{$mime_boundary}--\n";
// now we just send the message
if (#mail($to, $subject, $message, $headers))
echo "Message Sent";
else
echo "Failed to send";
} else {
?>
<p>Send an e-mail with an attachment:</p>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="multipart/form-data" name="form1">
<p>Your name: <input type="text" name="fromname"></p>
<p>Your e-mail: <input type="text" name="fromemail"></p>
<p>Mod List: <textarea name="question" maxlength="1000" cols="25" rows="6" name="modlist"></textarea>
<p>File: <input type="file" name="file1"></p>
<p>File: <input type="file" name="file2"></p>
<p>File: <input type="file" name="file3"></p>
<p>File: <input type="file" name="file4"></p>
<p>File: <input type="file" name="file5"></p>
<p>File: <input type="file" name="file6"></p>
<p>File: <input type="file" name="file7"></p>
<p><input type="submit" name="Submit" value="Submit"></p>
</form>
<?php } ?>
</body>
</html>

Submit form with attachment to email

My code here is:
<form action="#" method="POST" enctype="multipart/form-data" >
<input type="file" name="csv_file[]" />
<br/>
<input type="file" name="csv_file[]" />
<br/>
<input type="file" name="csv_file[]" />
<br/>
<input type="submit" name="upload" value="Upload" />
<br/>
</form>
<?php
if($_POST) {
for($i=0; $i < count($_FILES['csv_file']['name']); $i++){
$ftype[] = $_FILES['csv_file']['type'][$i];
$fname[] = $_FILES['csv_file']['name'][$i];
}
// array with filenames to be sent as attachment
$files = $fname;
// email fields: to, from, subject, and so on
$to = "example#gmail.com";
$from = "example#gmail.com";
$subject ="My subject";
$message = "My message";
$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 = "This is a multi-part message in MIME format.\n\n" . "--{$mime_boundary}\n" . "Content-Type: text/plain; charset=\"iso-8859-1\"\n" . "Content-Transfer-Encoding: 7bit\n\n" . $message . "\n\n";
$message .= "--{$mime_boundary}\n";
// preparing attachments
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";
}
// send
$ok = #mail($to, $subject, $message, $headers);
if ($ok) {
echo "<p>mail sent to $to!</p>";
} else {
echo "<p>mail could not be sent!</p>";
}
}
?>
I got the code from here: https://stackoverflow.com/a/27565430/4357238
the form successfully sends the email and when i get the email, the name of the file(s) show up but the file is an empty file (0 bytes).
For example, i send a file called car.jpg and when it gets to my email, it shows up on my email as car.jpg but when i download the file and open the file, it says the file is broken and it cannot be opened because the file is empty.
what is wrong and how can i fix it?

File not being attached for mailing

I have been trying to create a html form for users to send a mail with an attachment using the php mail function. The mail gets sent successfully but without the attachment. When i tried to check the file being uploaded I don't seem to be getting the file selected by the user. Below is my html code
<form name="message" id="message" method="post" action="mail.php" enctype="multipart/form-data">
<input type="text" class ="text-class" id="name" name="name" placeholder="Name*" required/>
<input type="email" class ="text-class" placeholder="Email*" name="Email" id ="Email" required/>
<textarea class ="text-class" placeholder="Message*" name="Message" id="Message" required></textarea>
<div class="captcha">
<div class="row">
<div class="4u">
<input class ="text-class" type="text" value="2 + 3 is ?" name="question" readonly/>
</div>
<div class="8u">
<input class ="text-class" type="text" placeholder="Answer*" name="captcha" id="captcha" required/>
</div>
</div>
</div>
<input type="hidden" name="MAX_FILE_SIZE" value="30000" />
<input type="file" name="attachment" id="attachment"/>
<input type="submit" name="Submit" value="Send" class="submit"/>
</form>
mail.php
<?php
if(isset($_POST['Submit']) && ($_POST['Submit']) == 'Send' )
{
// Checking For Blank Fields..
if($_POST["name"]==""||$_POST["Email"]==""||$_POST["Message"]==""){
echo "Fill All Fields..";
}else{
// Check if the "Sender's Email" input field is filled out
$email=$_POST['Email'];
// Sanitize E-mail Address
$email =filter_var($email, FILTER_SANITIZE_EMAIL);
// Validate E-mail Address
$email= filter_var($email, FILTER_VALIDATE_EMAIL);
if (!$email){
echo "Invalid Sender's Email";
}
else{
$message = $_POST['Message'];
$headers = 'From:'. $email . "\r\n"; // Sender's Email
/* GET File Variables */
$tmpName = $_FILES['attachment']['tmp_name'];
$fileType = $_FILES['attachment']['type'];
$fileName = $_FILES['attachment']['name'];
if((empty($_POST['attachment'])) || (empty($_FILES['attachment']))){
echo "No attachement!";
}
else{
//file is attached, process it and send via mail
$file = fopen($tmpName,'rb');
$data = fread($file,filesize($tmpName));
fclose($file);
$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";
mail("mail#test.com", "Mail from my website", $message, $headers);
echo "Your message has been received by us ! Thank you for contacting us";
echo "<script>
alert('Your message has been sent!');
</script>";
}
exit;
}
}
}else{
echo "Not submitted";
}
?>
I get "No attachment" messaged echoed since I don't seem to be getting the selected file from the html form. Please can someone tell me where I'm going wrong?

Email HTML form submissions with csv file attachment - receiving multiple emails

I've been asked to create a form that on submission sends the admin an email with a .csv attachment of the collated data.
I've scoured the internet and found this solution, and it works! However on submission I get about 3-4 emails (it seems to vary). Is this the code, or am I already receiving spam?
HTML Form:
<form method="post">
<p>Enter your email address
<input type="text" name="email" size="50" />
</p>
<p>Please add your first name
<input type="text" name="firstName" size="20" />
</p>
<p>Please add your last name
<input rows="2" name="lastName" size="20"></input>
</p>
<p> </p>
<p> </p>
<p>
<input type="submit" value="Submit" name="B1" />
<input type="reset" value="Reset" name="B2" />
</p>
</form>
PHP Code:
<?php
$email=$_REQUEST['email'];
$firstName=$_REQUEST['firstName'];
$lastName=$_REQUEST['lastName'];
$to = "test#testmail.co.uk";
$subject = "Test subject";
$message = "".
"Email: $email" . "\n" .
"First Name: $firstName" . "\n" .
"Last Name: $lastName";
//The Attachment
$cr = "\n";
$data = "Email" . ',' . "First Name" . ',' . "Last Name" . $cr;
$data .= "$email" . ',' . "$firstName" . ',' . "$lastName" . $cr;
$fp = fopen('diploma_apprenticeship_form_sub.csv','a');
fwrite($fp,$data);
fclose($fp);
$attachments[] = Array(
'data' => $data,
'name' => 'diploma_apprenticeship_form_sub.csv',
'type' => 'application/vnd.ms-excel'
);
//Generate a boundary string
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
//Add the headers for a file attachment
$headers = "MIME-Version: 1.0\n" .
"From: {$from}\n" .
"Content-Type: multipart/mixed;\n" .
" boundary=\"{$mime_boundary}\"";
//Add a multipart boundary above the plain 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" .
$text . "\n\n";
//Add sttachments
foreach($attachments as $attachment){
$data = chunk_split(base64_encode($attachment['data']));
$name = $attachment['name'];
$type = $attachment['type'];
$message .= "--{$mime_boundary}\n" .
"Content-Type: {$type};\n" .
" name=\"{$name}\"\n" .
"Content-Transfer-Encoding: base64\n\n" .
$data . "\n\n" ;
}
$message .= "--{$mime_boundary}--\n";
mail($to, $subject, $message, $headers);
?>
Thanks in advance,
Matt
In the end I just added an if statement that says if the email field equals nothing don't send any emails. This stops the email being triggered when the page is loaded, and an email when the page resets after submission - hence why I was getting 3 emails!

Categories