Php form upload and email - php

I have the following code, ideally, it is expected that the user shall upload a file(image/video) when submitting the form, but it is not compulsory though.
<?php
$to = "someone#example.com";
$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";
}
?>
<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="Contact.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>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>
</body>
<html>
The problem that i am facing is,
it runs on page load, and
if file has not been uploaded, it throws a warning.
I tried putting the file upload part under "if filename exists" condition, but then the email does not send the attachment
Please help.
This file name is Contact.php

it runs on page load
enclose mail send feature in
if(isset($_POST['Submit']) && ($_POST['Submit']) == 'Send' )
{
/* process only when submit button whose name='Submit'
and value= 'Send' is pressed
entire PHP code */
}
if file has not been uploaded, it throws a warning.
check before attaching it in PHP
if((empty($_POST['attachment'])) || (empty($_FILES['attachment']))){
//file is not attached, show error
}else{
//file is attached, process it and send via mail
}

Related

How can i upload images to mail using PHP form

How can I upload to send multiple images via PHP form without using SMTP or login to a spesific Email Account?
My code only works with one input of File type and I want to use 4 inputs to be able to show all 4 images in the mail.
When I try to add more than one File input it gets 'Error in Email sending'.
What should i do?
Here is my code:
<form action="sendmail.php" method="post" name="mainform" enctype="multipart/form-data">
<table width="500" border="0" cellpadding="5" cellspacing="5">
<tr>
<th>Attach Your File</th>
<td><input name="attachment" type="file"></td>
</tr>
<tr>
<th>Attach Your File</th>
<td><input name="attachment2" type="file"></td>
</tr>
<tr>
<th>Attach Your File</th>
<td><input name="attachment3" type="file"></td>
</tr>
<tr>
<th>Attach Your File</th>
<td><input name="attachment4" 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
$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";
}
?>
It's not very well to post a big bunch of code and ask for analyzing it. ;-)
Generally: Try to write the data stream you want to send to a file and then analyze it - manually or with some kind of mail tool (could even be a mail client which issue warnings). Try to construct manually a valid email with multiple attachments and then try to reproduce the format with your code.
In your case: I see an issue which is not directly related to "issue with multiple files" but an issue about the content type (thus I'm not writing a comment but an answer): charset iso-8859-1 should not be used with "7bit" but with "8bit" or "quoted-printable" encoding.
EDIT1: Fix bad english.
EDIT2: Read your code again. I don't see any \r for CRLF line endings.

How to show the success message of PHP in html page on Form submission

I am developing website in html. In Careers.html page i am having Apply button. On clicking that apply button it will send the mail using php file. On suceess event i need to set the alert or to show the div on the same Careers.html page.
Careers.html
<form method="post" action="Applyresume.php" enctype="multipart/form-data">
<tr>
<td>First Name </td>
<td><input type="TextBox" name="First_Name" class="applytext" required></td>
</tr>
<tr>
<td>Last Name </td>
<td><input type="TextBox" name="Last_Name" class="applytext" required></td>
</tr>
<tr>
<td>E-mail </td>
<td><input type="TextBox" name="email" class="applytext" required></td>
</tr>
<tr>
<td>Phone </td>
<td><input type="TextBox" name="Phone_No" class="applytext" required></td>
</tr>
<tr>
<td>Attachment </td>
<td><input type="file" name="attachment" maxlength="50" allow="text/*" class="applytext" required></td>
</tr>
<tr>
<td colspan="2"><input type="submit" name="button" class="send-resume" value="SEND" style="margin-left:24%;">
<input type="reset" value="RESET" style="margin-left:8%"></td>
</tr>
</form>
Applyresume.php
<?php
if($_POST && isset($_FILES['attachment']))
{
$name= $_POST['First_Name'];
$lname= $_POST['Last_Name'];
$email= $_POST['email'];
$phonenum = $_POST['Phone_No'];
$from_email = $_POST['email']; //sender email
$recipient_email = 'nisha#acute.company'; //recipient email
$subject = 'Test Email '; //subject of email
$message = 'Resume attached below.'; //message body
$emailbod = "$name
$lname
$email
$phonenum";
//get file details we need
$file_tmp_name = $_FILES['attachment']['tmp_name'];
$file_name = $_FILES['attachment']['name'];
$file_size = $_FILES['attachment']['size'];
$file_type = $_FILES['attachment']['type'];
$file_error = $_FILES['attachment']['error'];
$user_email = filter_var($_POST["email"], FILTER_SANITIZE_EMAIL);
if($file_error>0)
{
die('upload error');
}
//read from the uploaded file & base64_encode content for the mail
$handle = fopen($file_tmp_name, "r");
$content = fread($handle, $file_size);
fclose($handle);
$encoded_content = chunk_split(base64_encode($content));
$boundary = md5("sanwebe");
//header
$headers = "MIME-Version: 1.0\r\n";
$headers .= "From:".$from_email."\r\n";
$headers .= "Reply-To: ".$user_email."" . "\r\n";
$headers .= "Content-Type: multipart/mixed; boundary = $boundary\r\n\r\n";
//plain text
$body = "--$boundary\r\n";
$body .= "Content-Type: text/plain; charset=ISO-8859-1\r\n";
$body .= "Content-Transfer-Encoding: base64\r\n\r\n";
$body .= chunk_split(base64_encode($emailbod));
//attachment
$body .= "--$boundary\r\n";
$body .="Content-Type: $file_type; name=\"$file_name\"\r\n";
$body .="Content-Disposition: attachment; filename=\"$file_name\"\r\n";
$body .="Content-Transfer-Encoding: base64\r\n";
$body .="X-Attachment-Id: ".rand(1000,99999)."\r\n\r\n";
$body .= $encoded_content;
$sentMail = #mail($recipient_email, $subject, $body, $headers);
if($sentMail) //output success or failure messages
{
echo '<script type="text/javascript">alert("Thanks for your interest. Your Resume has been sent to HR#prominData.com");window.location.assign("Careers.html");</script>';
}else
{
echo"<script>alert('Could not send mail! Please check your PHP mail configuration.')</script>";
}
}
?>
My problem is I need to set the success alert in the same html page.
But here my success alert is opening in PHP page.
How to add this php code in same html page?
To view the message or alert on the same page, you can just copy your php code in the same HTML page. Do it as below
your_html.php
<form method="post" action="" enctype="multipart/form-data">
<tr>
<td>First Name </td>
<td><input type="TextBox" name="First_Name" class="applytext" required></td>
</tr>
<tr>
<td>Last Name </td>
<td><input type="TextBox" name="Last_Name" class="applytext" required></td>
</tr>
<tr>
<td>E-mail </td>
<td><input type="TextBox" name="email" class="applytext" required></td>
</tr>
<tr>
<td>Phone </td>
<td><input type="TextBox" name="Phone_No" class="applytext" required></td>
</tr>
<tr>
<td>Attachment </td>
<td><input type="file" name="attachment" maxlength="50" allow="text/*" class="applytext" required></td>
</tr>
<tr>
<td colspan="2"><input type="submit" name="button" class="send-resume" value="SEND" style="margin-left:24%;">
<input type="reset" value="RESET" style="margin-left:8%"></td>
</tr>
</form>
<?php
if($_POST && isset($_FILES['attachment']))
{
$name= $_POST['First_Name'];
$lname= $_POST['Last_Name'];
$email= $_POST['email'];
$phonenum = $_POST['Phone_No'];
$from_email = $_POST['email']; //sender email
$recipient_email = 'nisha#acute.company'; //recipient email
$subject = 'Test Email '; //subject of email
$message = 'Resume attached below.'; //message body
$emailbod = "$name
$lname
$email
$phonenum";
//get file details we need
$file_tmp_name = $_FILES['attachment']['tmp_name'];
$file_name = $_FILES['attachment']['name'];
$file_size = $_FILES['attachment']['size'];
$file_type = $_FILES['attachment']['type'];
$file_error = $_FILES['attachment']['error'];
$user_email = filter_var($_POST["email"], FILTER_SANITIZE_EMAIL);
if($file_error>0)
{
die('upload error');
}
//read from the uploaded file & base64_encode content for the mail
$handle = fopen($file_tmp_name, "r");
$content = fread($handle, $file_size);
fclose($handle);
$encoded_content = chunk_split(base64_encode($content));
$boundary = md5("sanwebe");
//header
$headers = "MIME-Version: 1.0\r\n";
$headers .= "From:".$from_email."\r\n";
$headers .= "Reply-To: ".$user_email."" . "\r\n";
$headers .= "Content-Type: multipart/mixed; boundary = $boundary\r\n\r\n";
//plain text
$body = "--$boundary\r\n";
$body .= "Content-Type: text/plain; charset=ISO-8859-1\r\n";
$body .= "Content-Transfer-Encoding: base64\r\n\r\n";
$body .= chunk_split(base64_encode($emailbod));
//attachment
$body .= "--$boundary\r\n";
$body .="Content-Type: $file_type; name=\"$file_name\"\r\n";
$body .="Content-Disposition: attachment; filename=\"$file_name\"\r\n";
$body .="Content-Transfer-Encoding: base64\r\n";
$body .="X-Attachment-Id: ".rand(1000,99999)."\r\n\r\n";
$body .= $encoded_content;
$sentMail = #mail($recipient_email, $subject, $body, $headers);
if($sentMail) //output success or failure messages
{
echo '<script type="text/javascript">alert("Thanks for your interest. Your Resume has been sent to HR#prominData.com");window.location.assign("Careers.html");</script>';
}else
{
echo"<script>alert('Could not send mail! Please check your PHP mail configuration.')</script>";
}
}
?>
Dont forget to remove the action attribute of <form>. Also the extension of your HTML page should be changed to php.
set a condition on success
create a session
$_SESSION['action] = "Your Massage";
and when page refresh.
there would be a place where you want to echo that massage.

PHP - Upload file from client to server

I need to know how I can take a file (.txt or else) from a client PC and upload it into some directory on server where I have the site that needs than to send an e-mail with this file as attachment (but this is not a problem anymore). This has to be done by a PHP function. Can anybody help me, please?
Form content:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
</head>
<body>
<form action="sendEmail.php" method="post" name="mainform" enctype="multipart/form-data">
<table width="500" border="0" cellpadding="5" cellspacing="5">
<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>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 File"></td>
</tr>
</table>
</form>
</body>
</html>
Script to handle:
<?php
$to = $_POST['toEmail'];
$subject = $_POST['fieldSubject'];
// Get file info
$tmpName = $_FILES['attachment']['tmp_name'];
$fileType = $_FILES['attachment']['type'];
$fileName = $_FILES['attachment']['name'];
if (file($tmpName)) {
$file = fopen($tmpName,'rb');
$data = fread($file,filesize($tmpName));
fclose($file);
$randomVal = md5(time());
$mimeBoundary = "==Multipart_Boundary_x{$randomVal}x";
$headers = "From: $fromName";
$headers .= "\nMIME-Version: 1.0\n";
$headers .= "Content-Type: multipart/mixed;\n" ;
$headers .= " boundary=\"{$mimeBoundary}\"";
$message = "This is test email\n\n";
$data = base64_encode($data);
}
$result = mail ("$to", "$subject", "$message", "$headers");
if($result){
echo "A email has been sent to: $to";
}
else{
echo "Error while sending email";
}

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

Multiple file upload together with excel form [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
We presently have a form that when submitted the user responses are emailed to us as an attached excel file. We also have another form that allows the user to upload multiple files of various types which are then emailed to us as attachments. However we have been unable to combine the two into one form, so that we can receive an email with both types of attachments. We are beginners...
Below is:
1. The existing form which attaches the single excel content
2. the existing mailer.php
3. the existing form which uploads multiple files
1. excel content form
<?php
error_reporting(E_ALL ^ E_NOTICE);
ob_start();
$taxyear = $_POST['taxyear'];
$company = $_POST['company'];
$tfn = $_POST['tfn'];
$director1 = $_POST['director1'];
$director2 = $_POST['director2'];
$email = $_POST['email'];
?>
<html>
<body>
<form>
<table width="720" border="0" align="center" bgcolor="#FFFFFF">
<tr align="center" valign="top">
<td height="1730">COMPANY RETURN
<table width="702" border="1" align="center" cellpadding="0" cellspacing="0" bgcolor="#FFFFFF">
<tr>
<td colspan="6" align="left" class="whiteonred" >Company <strong><? echo $taxyear; ?> </strong></td>
</tr>
<tr class="excel7" style="height:18.0pt;">
<td colspan="4" align="left" class="centgothicstd" ><strong>PRINCIPAL DETAILS </strong></td>
<td colspan="2" align="right" class="centgothicsm"> </td>
</tr>
<tr style="height:18.0pt;">
<td align="left" class="centgothicsm" >COMPANY NAME & TFN</td>
<td colspan="3" align="left" class="borders"><strong><? echo $company; ?></strong></td>
<td colspan="2" align="left" class="borders"><strong><? echo $tfn; ?></strong></td>
</tr>
<tr style="height:18.0pt;">
<td width="213" align="left" class="centgothicsm" style="height:18.0pt;">DIRECTOR NAMES</td>
<td colspan="3" align="left" class="borders"><? echo $director1; ?></td>
<td colspan="2" align="left" class="borders"><? echo $director2; ?></td>
</tr>
<tr style="height:18.0pt;">
<td width="213" align="left" class="centgothicsm" style="height:18.0pt;">EMAIL ADDRESS</td>
<td colspan="5" align="left" class="borders"><? echo $email; ?></td>
</tr>
</table></td>
</tr>
</table>
</form>
</body>
</html>
<?php
$FILE_CONTENTS = ob_get_contents();
ob_clean();
include("mailer.php");
$recipient = "darren#eto.net.au";
$subject = "Company submission";
$myEmail = new EPDEV_Emailer($recipient, $email, $subject);
$myEmail->addFile("{$company}-{$taxyear}.xls", "application/vnd.ms-excel", $FILE_CONTENTS);
$myEmail->send();
Header("Location: thankyouapplic.htm");
?>
*2. the mailer.php code *
<?php
class EPDEV_Emailer
{
var $message;
var $FILES;
var $EMAIL;
function EPDEV_Emailer($to_address, $from_address, $subject, $reply_address=null, $mailer=null, $custom_header=null)
{
$this->EMAIL = array(
"to" => $to_address,
"from" => $from_address,
"subject" => $subject,
"reply" => (empty($reply_address) ? $from_address : $reply_address),
"mailer" => (empty($mailer) ? "X-Mailer: PHP/" . phpversion() : $mailer),
"header" => (empty($custom_header) ? "" : $custom_header),
"boundary" => "_mimeboundary_".md5(uniqid(mt_rand(), 1))
);
$this->message = "";
$this->FILES = array();
}
function addFile($filename, $type=null, $filecontents=null)
{
if ($filecontents !== null)
{
$index = count($this->FILES);
$this->FILES[$index]['data'] = chunk_split(base64_encode($filecontents));
$this->FILES[$index]['name'] = basename($filename);
if (empty($type))
$this->FILES[$index]['mime'] = mime_content_type($filename);
else
$this->FILES[$index]['mime'] = $type;
}
else if (file_exists($filename))
{
$index = count($this->FILES);
$this->FILES[$index]['data'] = chunk_split(base64_encode(file_get_contents($filename)));
$this->FILES[$index]['name'] = basename($filename);
if (empty($type))
$this->FILES[$index]['mime'] = mime_content_type($filename);
else
$this->FILES[$index]['mime'] = $type;
}
else
{
$this->Error_Handle("File specified -- {$filename} -- does not exist.");
}
}
function addText($text)
{
$this->message .= $text;
}
function getHeader()
{
$header = "From: {$this->EMAIL['from']}\r\n"
. "Reply-To: {$this->EMAIL['reply']}\r\n"
. "X-Mailer: {$this->EMAIL['mailer']}\r\n"
. "MIME-Version: 1.0\r\n"
. "Content-Type: multipart/mixed; boundary=\"{$this->EMAIL['boundary']}\";\r\n";
return $header;
}
function getEmail()
{
$content .= "--{$this->EMAIL['boundary']}\r\n"
. "Content-Type: text/plain; charset=\"iso-8859-1\"\r\n"
. "Content-Transfer-Encoding: 7bit\r\n\r\n"
. $this->message . "\r\n";
if (!empty($this->FILES))
{
foreach($this->FILES as $file)
{
$content .= "--{$this->EMAIL['boundary']}\r\n"
. "Content-Type: {$file['mime']}; name=\"{$file['name']}\"\r\n"
. "Content-Transfer-Encoding: base64\r\n"
. "Content-Disposition: attachment\r\n\r\n"
. $file['data'] . "\r\n";
}
}
$content .= "--{$this->EMAIL['boundary']}--\r\n";
return $content;
}
function send()
{
$result = mail($this->EMAIL['to'], $this->EMAIL['subject'], $this->getEmail(), $this->getHeader());
if (!$result)
$this->Error_Handle("The email failed to send.");
}
function Error_Handle($error)
{
die($error);
}
}
3. the upload form
<body>
<td height="353" colspan="9" align="left" valign="top">
<form enctype="multipart/form-data" name="send" method="post" action="<?=$_SERVER['PHP_SELF']?>">
<input type="hidden" name="action" value="send" />
<input type="hidden" name="MAX_FILE_SIZE" value="10000000" />
<tr>
<td width="300" align="center"> </td>
<table width="500" height="407" border="0" align="center">
<tr>
<td width="120" align="left" class="indextextlight">Name:</td>
<td colspan="2"><input name="fname" type="text" class="indextextlight" size="30" /></td>
</tr>
<tr>
<td width="120" height="24" align="left" class="indextextlight">E-mail:</td>
<td colspan="2"><label>
<input name="email" type="text" class="indextextlight" size="30" />
</label></td>
</tr>
<tr>
<td width="120" align="left" class="indextextlight">Telephone:</td>
<td colspan="2"><label>
<input name="tel" type="text" class="indextextlight" id="tel" value="" size="15" />
</label></td>
</tr>
<tr>
<td width="120" align="left" valign="top" class="indextextlight">Message:
</td>
<td colspan="2" valign="top"><textarea name="comments" " id="comments" cols="45" rows="4"></textarea></td>
</tr>
<tr>
<td width="120" valign="middle" class="indextextlight">Upload Files:</td>
<td colspan="2"><p>
<input name="attachment[]" type="file" multiple="" class="indextextlight" size="42">
<br />
<span class="centgothicmini"> note - hold the Ctrl key to select multiple files</span><br />
<span class="centgothicmini"> note - max total size of all files can not exceed 10mb</span></td>
</tr>
<tr>
<td width="120" align="left" class="indextextlight">Send:</td>
<td colspan="2" align="left"><input type="image" name="submit" value="Send Email" src="images/btnSubmit.gif" /></td>
</tr>
<tr>
<td width="120" class="indextextlight">Result:</td>
<td colspan="2" class="header"><?php
/* Mailer with Attachments */
$action = $_REQUEST['action'];
global $action;
function showform(){
?></td>
</tr>
<tr>
<td class="indextextlight"> </td>
<td colspan="2" class="header"> </td>
</tr>
<tr><td colspan="3" align="right" valign="baseline" class="footer"><span class="footerheadings"> </span> © 2009-13 BC Accountants Australia Pty Ltd</td>
</tr>
</table>
</form>
<script type="text/javascript">
var frmvalidator = new Validator("send");
frmvalidator.addValidation("fname","req","Please enter your Name");
frmvalidator.addValidation("email","maxlen=50");
frmvalidator.addValidation("email","req");
frmvalidator.addValidation("email","email");
frmvalidator.addValidation("tel","maxlen=15");
frmvalidator.addValidation("tel","numeric");
</script>
<?php
}
function sendMail() {
if (!isset ($_POST['email'])) { //Oops, forgot your email addy!
die ("<p>Oops! You forgot to fill out the email address! Click on the back arrow to go back</p>");
}
else {
$fname = stripslashes($_POST['fname']);
$email = $_POST['email'];
$phone = $_POST['tel'];
$comments = stripslashes($_POST['comments']);
$headers .= "\n";
//Uniqid session
$strSid = md5(uniqid(time()));
//Let's start our headers
$headers = "From: $fname<" . $_POST['email'] . ">\n";
$headers .= "Reply-To: <" . $_POST['email'] . ">\n";
$headers .= "MIME-Version: 1.0\n";
$headers .= "Content-Type: multipart/mixed; boundary=\"".$strSid."\"\n\n";
$headers .= "This is a multi-part message in MIME format.\n";
$headers .= "--".$strSid."\n";
$headers .= "Content-type: text/html; charset=utf-8\n";
$headers .= "Content-Transfer-Encoding: 7bit\n\n";
/* Add our message, in this case it's plain text. You could also add HTML by changing the Content-Type to text/html */
$headers .= "<table>";
$headers .= "<tr><td>CONTACT FORM</td><td> </td></tr>";
$headers .= "<tr><td>Check for attachments</td><td> </td> </tr>";
$headers .= "<tr>
<td> </td>
<td > </td>
</tr>";
$headers .= "<tr>
<td >Name: " . strip_tags($_POST["fname"]) . "</td><td > </td>
</tr>";
$headers .= "<tr>
<td>Email: " . strip_tags($_POST["email"]) . "</td><td > </td>
</tr>";
$headers .= "<tr>
<td>Phone: " . strip_tags($_POST["phone"]) . "</td><td> </td>
</tr>";
$headers .= "<tr>
<td> </td>
<td > </td>
</tr>";
$headers .= "<tr>
<td>MESSAGE</td><td> </td></tr>";
$headers .= "<tr> <td COLSPAN = '2'>" . strip_tags($_POST["comments"]) . "</td>
</tr>";
$headers .= "<tr>
<td> </td>
<td > </td>
</tr>";
$headers .= "</table>";
$headers .= "</body></html>";
$headers .= "\n";
//**multi attach**//
for($i=0;$i<count($_FILES["attachment"]["name"]);$i++)
{
if($_FILES["attachment"]["name"][$i] != "")
{
$file_name = $_FILES["attachment"]["name"][$i];
$data = chunk_split(base64_encode(file_get_contents($_FILES["attachment"]["tmp_name"][$i])));
$headers .= "--".$strSid."\n";
$headers .= "Content-Type: application/octet-stream;\n\tname=\"" . $file_name . "\"\n";
$headers .= "Content-Transfer-Encoding: base64\n";
$headers .= "Content-Disposition: attachment;\n\tfilename=\"" . $file_name . "\"\n\n";
$headers .= $data."\n\n"; //The base64 encoded message
}
}
$headers .= "\n";
$headers .= "------=MIME_BOUNDRY_main_message--\n";
$subject .= "Contact Form";
// send the message
mail("darrenmillbca#gmail.com", $subject, $message, $headers);
print "Mail sent. Thank you!";
$to = $email;
$subject = "Contact Form";
$message = '
<html>
<body>
<p>Dear ';
$message .= $fname;
$message .= '</p>
<p>Thankyou for your message. </p>
<p>Our staff will get back to you shortly. </p>
<p>Kind Regards <br />
<br />
</p>
</body>
</html>
';
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
// Additional headers
$headers .= 'To:' . "\r\n";
$headers .= 'From: darrenmillbca#gmail.com' . "\r\n";
//$headers .= 'Cc: birthdayarchive#example.com' . "\r\n";
//$headers .= 'Bcc: birthdaycheck#example.com' . "\r\n";
// Mail it
mail($to, $subject, $message, $headers);
}
}
switch ($action) {
case "send":
sendMail();
showForm();
break;
default:
showForm();
}
?>
</html>
What you're asking for is quite a significant change here, so I'll try my best to make it simple for you guys. Your excel content form makes use of an email wrapper (mailer.php) which converts attaching files to an email to just $myEmail->addFile("file name","mimetype","file content"). The upload form on the other hand is not using this wrapper and is instead generating a whole email seperately. So you'll want to focus on moving your uploads to utilising the wrapper; that's moving content from the uploads form to the excel form.
So, our focus is with the following block from the uploads file:
for($i=0;$i<count($_FILES["attachment"]["name"]);$i++)
{
if($_FILES["attachment"]["name"][$i] != "")
{
$file_name = $_FILES["attachment"]["name"][$i];
$data = chunk_split(base64_encode(file_get_contents($_FILES["attachment"]["tmp_name"][$i])));
$headers .= "--".$strSid."\n";
$headers .= "Content-Type: application/octet-stream;\n\tname=\"" . $file_name . "\"\n";
$headers .= "Content-Transfer-Encoding: base64\n";
$headers .= "Content-Disposition: attachment;\n\tfilename=\"" . $file_name . "\"\n\n";
$headers .= $data."\n\n"; //The base64 encoded message
}
Which is saying 'for each file upload, write it into the email we're building up'. Instead of this, we want to do 'for each file upload, attach it using the wrapper'. That would be done like so:
for($i=0;$i<count($_FILES["attachment"]["name"]);$i++){
if($_FILES["attachment"]["name"][$i] != "")
{
$file_name = $_FILES["attachment"]["name"][$i];
$data = file_get_contents($_FILES["attachment"]["tmp_name"][$i]);
$myEmail->addFile($file_name,"application/octet-stream",$data);
}
}
For this to work, the above code would go in your excel form right after the existing $myEmail->addFile call. In other words, right after you attach your excel sheet, look for any attachments, then add those to the email too:
$myEmail->addFile("{$company}-{$taxyear}.xls", "application/vnd.ms-excel", $FILE_CONTENTS);
// Drop it right here.
$myEmail->send();
So far so good - at this point, your excel form can handle multiple uploads, but it can't create them. To fix that, you'll then want to start transferring the html that allows your users to upload files over to your excel form. That's this part:
<tr>
<td width="120" valign="middle" class="indextextlight">Upload Files:</td>
<td colspan="2"><p>
<input name="attachment[]" type="file" multiple="" class="indextextlight" size="42">
<br />
<span class="centgothicmini"> note - hold the Ctrl key to select multiple files</span><br />
<span class="centgothicmini"> note - max total size of all files can not exceed 10mb</span></td>
</tr>
<tr>
A simple thing you could do is dump that wherever it fits on your excel form and as a result your excel form should then accept multiple uploads. From there, all that is required is transferring any other fields you want from upload to excel :)

Categories