PHP Form Upload - Extension invalid when file left blank - php

I have a php form which allows multiple uploads of the accepted extentions:
$allowedExtensions = array("pdf","doc","docx","gif","jpeg","jpg","png","rtf","txt");
If extention isn't valid it enters this:
if(!in_array($ext,$allowedExtensions)) {
die("File $file_name has the extensions $ext which is not allowed");
}
At the moment I'm getting the error "File has the extensions which is not allowed" when a field is left blank. I have tried adding into the array an empty" ", is that what a blank file's extention would be?
What is the best way around this? Would it be to load in preset image when not filled in or does someone have a solution?
Here is the source code, maybe can help someone else:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
if(isset($_FILES) && (bool) $_FILES) {
$allowedExtensions = array("pdf","doc","docx","gif","jpeg","jpg","png","rtf","txt");
$files = array();
foreach($_FILES as $name=>$file) {
$file_name = $file['name'];
$temp_name = $file['tmp_name'];
$file_type = $file['type'];
$path_parts = pathinfo($file_name);
$ext = $path_parts['extension'];
if(!in_array($ext,$allowedExtensions)) {
die("File $file_name has the extensions $ext which is not allowed");
}
array_push($files,$file);
}
// email fields: to, from, subject, and so on
$to = "<info#xxx.co.uk>";
$from = "<info#xxx.co.uk>";
$subject ="test attachment";
$message = "this is a test message";
$headers = "From: $from";
$band = $_POST['band'];
// 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 = $band;
$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]['tmp_name'],"rb");
$data = fread($file,filesize($files[$x]['tmp_name']));
fclose($file);
$data = chunk_split(base64_encode($data));
$name = $files[$x]['name'];
$message .= "Content-Type: {\"application/octet-stream\"};\n" . " name=\"$name\"\n" .
"Content-Disposition: attachment;\n" . " filename=\"$name\"\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>photos sent!</p>";
} else {
echo "<p>mail could not be sent!</p>";
}
}
?>

Related

PHP: How to send emails with multiple attachments found in the same server

Here are the codes that works by receiving multiple files from HTML form. I need your assistance on how I can do the same while taking attachment files from the same server directory and not from HTML form anymore. Thanks.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
if(isset($_FILES) && (bool) $_FILES) {
$allowedExtensions = array("pdf","doc","docx","gif","jpeg","jpg","png","rtf","txt");
$files = array();
foreach($_FILES as $name=>$file) {
$file_name = $file['name'];
$temp_name = $file['tmp_name'];
$file_type = $file['type'];
$path_parts = pathinfo($file_name);
$ext = $path_parts['extension'];
if(!in_array($ext,$allowedExtensions)) {
die("File $file_name has the extensions $ext which is not allowed");
}
array_push($files,$file);
}
// email fields: to, from, subject, and so on
$to = "anold#insprogress.com";
$from = "we#insprogress.com";
$subject ="test attachment";
$message = "this is a test 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]['tmp_name'],"rb");
$data = fread($file,filesize($files[$x]['tmp_name']));
fclose($file);
$data = chunk_split(base64_encode($data));
$name = $files[$x]['name'];
$message .= "Content-Type: {\"application/octet-stream\"};\n" . " name=\"$name\"\n" .
"Content-Disposition: attachment;\n" . " filename=\"$name\"\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>";
}
}
?>
<input type="submit" value="submit"/>
</form>
</body>
As per the question you want to send the attachments available on the server current working directory.
thus the above file upload code can be removed from the code.
if the user wants to see the files present in the server you can make a AJAX request system which will contact the server for the files present in the directory and show them to the user.
for the above task you can refer the Directory Class functions to show the file names over the web page.
the above code for the attachments can be modified as:
$files = //the options selected by the user in an array
//don't forget to sanitize and check the data.
// preparing attachments
for($x=0;$x<count($files);$x++){
$file = fopen($files[$x],"rb");
$data = fread($file,filesize($files[$x]));
fclose($file);
...

mail attachment issue - why do i dont get the file properly?

i try to create a form with a option to upload files and to get it to my email .
for example that a user can put his info in the input fields and to add a file and when the user submit it i will get it all to my mail.
this is my code :
<?php
if(isset($_FILES) && (bool) $_FILES) {
$allowedExtensions = array("pdf","doc","docx","gif","jpeg","jpg","png","rtf","txt");
$files = array();
foreach($_FILES as $name=>$file) {
$file_name = $file['name'];
$temp_name = $file['tmp_name'];
$file_type = $file['type'];
$path_parts = pathinfo($file_name);
$ext = $path_parts['extension'];
if(!in_array($ext,$allowedExtensions)) {
die("File $file_name has the extensions $ext which is not allowed");
}
array_push($files,$temp_name);
}
// email fields: to, from, subject, and so on
$to = "dorozenman#gmail.com";
$from = $_POST['sender_email'];
$subject ="test attachment";
$message = "here ya go";
$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>";
}
}
?>
(and file arrive named... tmp/phpcVjk4w/ ) any suggestions?
Change:
array_push($files,$temp_name);
to:
array_push($files, array('temp_name' => $temp_name, 'file_name' => $file_name));
And change:
// 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";
}
To:
// preparing attachments
for($x=0;$x<count($files);$x++){
$temp_name = $files[$x]['temp_name']; // temporary file location
$file_name = $files[$x]['file_name']; // filename
$file = fopen($temp_name,"rb");
$data = fread($file,filesize($temp_name));
fclose($file);
$data = chunk_split(base64_encode($data));
$message .= "Content-Type: {\"application/octet-stream\"};\n" . " name=\"$file_name\"\n" .
"Content-Disposition: attachment;\n" . " filename=\"$file_name\"\n" .
"Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";
$message .= "--{$mime_boundary}\n";
}
The difference here is pulling the filename into the $files array along with the temporary file location. You need both, where is the file on the server, and what is the name of the file when uploaded.
Which is absolutely normal.
Basically, files are uploaded to your server, PHP temporary stores them in /tmp/ directory.
$files = array();
foreach($_FILES as $name=>$file) {
$temp_name = $file['tmp_name'];
array_push($files,$temp_name);
}
Above, you put that temporary name into an array, and below you put that name in your mail :
for($x=0;$x<count($files);$x++){
$message .= name=\"$files[$x]\"; //...
}
What do you want your script to do?

How to attach two or multiple files and send mail in PHP [duplicate]

This question already has answers here:
Send attachments with PHP Mail()?
(16 answers)
Sending multiple attachment in an email using PHP
(2 answers)
Closed 4 years ago.
The code below sends only one attachment, but I need to attach and send two file(one rar file and pdf)
$email_to = "$email"; // The email you are sending to (example)
$email_from = "online#example.co.in"; // The email you are sending from (example)
$email_subject = "subject line"; // The Subject of the email
$email_txt = "text body of message"; // Message that the email has in it
$fileatt = "files/example.rar"; // Path to the file (example)
$fileatt_type = "application/x-rar-compressed"; // File Type
$fileatt_name = "example.rar"; // Filename that will be used for the file as the attachment
$file = fopen($fileatt,'rb');
$data = fread($file,filesize($fileatt));
fclose($file);
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
$headers="From: $email_from"; // Who the email is from (example)
$headers .= "\nMIME-Version: 1.0\n" .
"Content-Type: multipart/mixed;\n" .
" boundary=\"{$mime_boundary}\"";
$email_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" . $email_txt;
$email_message .= "\n\n";
$data = chunk_split(base64_encode($data));
$email_message .= "--{$mime_boundary}\n" .
"Content-Type: {$fileatt_type};\n" .
" name=\"{$fileatt_name}\"\n" .
"Content-Transfer-Encoding: base64\n\n" .
$data . "\n\n" .
"--{$mime_boundary}--\n";
mail($email_to,$email_subject,$email_message,$headers);
<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>";
}
}
?>
Following the reusability principles, you can use https://github.com/Synchro/PHPMailer
<?php
require 'PHPMailerAutoload.php';
$mail = new PHPMailer;
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'smtp1.example.com;smtp2.example.com'; // Specify main and backup server
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'jswan'; // SMTP username
$mail->Password = 'secret'; // SMTP password
$mail->SMTPSecure = 'tls'; // Enable encryption, 'ssl' also accepted
$mail->From = 'from#example.com';
$mail->FromName = 'Mailer';
$mail->addAddress('josh#example.net', 'Josh Adams'); // Add a recipient
$mail->addAttachment('/var/tmp/file.tar.gz'); // Add attachments
$mail->addAttachment('/tmp/image.jpg', 'new.jpg'); // Optional name
$mail->Subject = 'Here is the subject';
$mail->Body = 'This is the HTML message body <b>in bold!</b>';
$mail->AltBody = 'This is the body in plain text for non-HTML mail clients';
if(!$mail->send()) {
echo 'Message could not be sent.';
echo 'Mailer Error: ' . $mail->ErrorInfo;
exit;
}
echo 'Message has been sent';
Check the following Multiple file attachment in core php mail function.
<?php
/** Mail with attachment */
function mail_attachment($filename, $path, $mailto, $from_mail, $from_name, $replyto, $bcc, $subject, $message){
$uid = md5(uniqid(time()));
$mime_boundary = "==Multipart_Boundary_x{$uid}x";
$header = "From: ".$from_name." <".$from_mail.">\r\n";
$header .= "Bcc: ".$bcc."\r\n";
$header .= "Reply-To: ".$replyto."\r\n";
$header .= "MIME-Version: 1.0\r\n";
$header .= "Content-Type: multipart/mixed; boundary=\"".$mime_boundary."\"\r\n\r\n";
$header .= "This is a multi-part message in MIME format.\r\n";
$header .= "--".$mime_boundary."\r\n";
$header .= "Content-type:text/html; charset=iso-8859-1\r\n";
$header .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
$header .= nl2br($message)."\r\n\r\n";
$header .= "--".$mime_boundary."\r\n";
foreach($filename as $k=>$v){
$file = $path.$v;
$file_size = filesize($file);
$handle = fopen($file, "r");
$content = fread($handle, $file_size);
fclose($handle);
$content = chunk_split(base64_encode($content));
$header .= "Content-Type: application/octet-stream; name=\"".$v."\"\r\n"; // use different content types here
$header .= "Content-Transfer-Encoding: base64\r\n";
$header .= "Content-Disposition: attachment; filename=\"".$v."\"\r\n\r\n";
$header .= $content."\r\n\r\n";
$header .= "--".$mime_boundary."--"."\r\n";
}
if (mail($mailto, $subject, "", $header)) {
//echo "mail send ... OK"; // or use booleans here
return true;
} else {
//echo "mail send ... ERROR!";
return false;
}
}
?>
This is one of the best solution i got for multiple mail attachment and tested successfully.
This code gives you freedom by attaching file in email without uploading in your hosting server space. Which is highly needed.
There are many solution telling how to upload files to your server and then send to email, but this solution gives "Direct multiple file attachment to email"
<!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="me#me.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}\"";
// here, we'll start the message body.
// this is the text that will be displayed
// in the e-mail
$message="This is an example";
$message .= "Name:".$_POST["fromname"]."Message Posted:".$_POST["modlist"];
// next, we'll build the invisible portion of the message body
// note that we insert two dashes in front of the MIME boundary
// 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";
// 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>File: <input type="file" name="file8"></p>
<p><input type="submit" name="Submit" value="Submit"></p>
</form>
<?php } ?>
</body>
</html>
Simple working and tested example:
<?php
mail_attachment("mail#mail.com","Subject","Here is the body",array("file1.pdf","file2.pdf"));
function mail_attachment($to, $subject, $message, $files) {
$headers = "From: no-reply#mail.com";
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
$headers .= "\nMIME-Version: 1.0\n" . "Content-Type: multipart/mixed;\n" . " boundary=\"{$mime_boundary}\"";
$message = "This is a multi-part message in MIME format.\n\n" . "--{$mime_boundary}\n" . "Content-Type: text/html; charset=\"iso-8859-1\"\n" . "Content-Transfer-Encoding: 7bit\n\n" . $message . "\n\n";
$message .= "--{$mime_boundary}\n";
foreach ($files as $file) {
$filename = end(explode("/",$file));
$data = file_get_contents($file);
$data = chunk_split(base64_encode($data));
$message .= "Content-Type: {\"application/octet-stream\"};\n" . " name=\"$file\"\n" .
"Content-Disposition: attachment;\n" . " filename=\"$file\"\n" .
"Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";
$message .= "--{$mime_boundary}\n";
}
echo (#mail($to, $subject, $message, $headers)) ? "<p>Send to $to!</p>" : "<p>Not send toaar $to!</p>";
} // mail-attachment
?>
Try this out. Put your files in an array, then using a form loop add each of them in the $email_message variable
$email_to = "$email"; // The email you are sending to (example)
$email_from = "online#example.co.in"; // The email you are sending from (example)
$email_subject = "subject line"; // The Subject of the email
$email_message = "text body of message"; // Message that the email has in it
$files = array("file_1.ext","file_2.ext","file_3.ext",......);
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
$headers="From: $email_from"; // Who the email is from (example)
$headers .= "\nMIME-Version: 1.0\n" .
"Content-Type: multipart/mixed;\n" .
" boundary=\"{$mime_boundary}\"";
$email_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" . $email_txt;
$email_message .= "\n\n";
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));
$email_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";
$email_message .= "--{$mime_boundary}\n";
}
mail($email_to,$email_subject,$email_message,$headers);
Hope it works fine :)
This is the code I am using to send multiple attachments, I hope this helps you too. You actually need to use a loop at attach multiple files.
$files = array("file1.pdf","file2.pdf");
$body = "email in html form";
// email fields: to, from, subject, and so on
$to = "e-mail id of person you are sending to";
$from = "your e-mail id";
$subject = "email subject";
$message = html_entity_decode($body);
$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/html; 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>";
}
<input type="file" name="file" multiple> //select multiple file
$target_dir = "upload/"; //first upload your directory path
$names = $_FILES['file']['name']; //file Name
$i =0;
foreach($names as $name){
$target_file = $target_dir . basename($name); //first upload your
directory path
move_uploaded_file($_FILES["file"]["tmp_name"][$i], $target_file);
//upload your directory
$mail->addAttachment($target_file); //after upload file path
fetch and atachment
$i++;
}
FYI, this line from the original post, as well as some of the answers, will cause a problem on some email systems.
$headers .= "\nMIME-Version: 1.0\n" .
The \n at the beginning caused the attachments to fail when sending to an address hosted at emailpros.com, a secure HIPAA compliant email system. Simply removing the line break fixed the issue there. However, it had been working just fine when sending to a Gmail account and another host (Hostmonster).
This way worked just fine on all of them.
$headers .= "MIME-Version: 1.0\n" .
<?php
// upload recommendation file section
$target_dir = "wp-content/uploads/rec_file/";
$target_file = $target_dir . basename($_FILES["RC_file"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
$check = getimagesize($_FILES["RC_file"]["tmp_name"]);
if($check !== false) {
$error_msg = "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
$error_msg = "File is not an image.";
$uploadOk = 0;
}
// Check if file already exists
if (file_exists($target_file)) {
$error_msg = "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["RC_file"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
$error_msg = "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
$error_msg = "your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["RC_file"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["RC_file"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file. ". $error_msg ;
}
}
// upload driven licence file section
$DL_target_dir = "wp-content/uploads/rec_file/";
$DL_target_file = $DL_target_dir . basename($_FILES["DL_file"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($DL_target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
$check = getimagesize($_FILES["DL_file"]["tmp_name"]);
if($check !== false) {
$error_msg = "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
$error_msg = "File is not an image.";
$uploadOk = 0;
}
// Check if file already exists
if (file_exists($DL_target_file)) {
$error_msg = "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["DL_file"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
$error_msg = "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
$error_msg = "your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["DL_file"]["tmp_name"], $DL_target_file)) {
echo "The file ". basename( $_FILES["DL_file"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file. ". $error_msg ;
}
}
// array with filenames to be sent as attachment
$files = array($target_file,$DL_target_file);
// email fields: to, from, subject, and so on
$to = "tkdilankumara#gmail.com";
$from = "help#soosti.com";
$subject ="Member Registration";
$headers = "From: $from";
$eol = "\r\n";
$message .= "Member Registration Information.".$eol;
$message .= $username.$eol;
$message .= $email.$eol;
$message .= $Fname.$eol;
$message .= $Lname.$eol;
$message .= $address.$eol;
// 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);
$content =file_get_contents($files[$x],"rb");
$content = chunk_split(base64_encode($content));
$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" . $content . "\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>";
}
?>

PHP - Attach multiple files to email, files attached are blank?!!?

This is just a sample of the code, essentially I have a form with 4 files to upload. The files are successfully saved on my server in a designated folder. However, I obviously am not attaching them properly since they are empty....can anyone help?
Also, the attachments disply the directory name instead of the file name...what am I missing?
Many thanks!!!
<?php
$username= protect($_POST['username']);
$firstName= protect($_POST['firstName']);
$lastName= protect($_POST['lastName']);
$email= protect($_POST['email']);
$program= protect($_POST['program']);
$dob= protect($_POST['dob']);
$transcript= $_FILES['transcript'];
$resume= $_FILES['resume'];
$letterIntent= protect($_POST['letterIntent']);
$reference1= $_FILES['reference1'];
$reference2= $_FILES['reference2'];
$relevantExperience= protect($_POST['relevantExperience']);
$volunteerExperience= protect($_POST['volunteerExperience']);
$reasonsAbroad= protect($_POST['reasonsAbroad']);
$definitionSuccess= protect($_POST['definitionSuccess']);
$futureGoals= protect($_POST['futureGoals']);
$challengeYourself= protect($_POST['challengeYourself']);
$challengeDevelopment= protect($_POST['challengeDevelopment']);
if (isset($_FILES) && (bool) $_FILES) {
$allowed_ext = array('doc', 'pdf', 'txt', '');
$files = array();
foreach($_FILES as $name=>$file) {
$file_name = $file['name'];
$file_tmp = $file['tmp_name'];
$file_size = $file['size'];
$path_parts = pathinfo($file_name);
$file_ext = $path_parts['extension'];
if(!in_array($file_ext, $allowed_ext)) {
die ("extension for file $file_name not allowed");
}
if($file_size > 2097152) {
die ("File size must be under 2MB");
}
$server_file = "wp-content/uploads/application-documents";
move_uploaded_file($file_tmp, "$server_file/$file_name");
array_push($files, $server_file);
}
$to = ".....#gmail.com";
$from = "$email";
$subject ="Application from $firstName $lastName with attachments";
$msg = "hello";
$headers = "From: $from";
//define email boundaries
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
$headers .= "\nMIME-Version: 1.0\n";
$headers .= "Content-Type: multipart/mixed;\n";
$headers .= " boundary=\"{$mime_boundary}\"";
$message ="\n\n--{$mime_boundary}\n";
$message .="Content-Type: text/plain; charset=\"iso-8859-1\"\n";
$message .="Content-Transfer-Encoding: 7bit\n\n" . $msg . "\n\n";
$message .= "--{$mime_boundary}\n";
foreach($files as $file) {
$aFile = fopen($file,"rb");
$data = fread($aFile,filesize($file));
fclose($aFile);
$data = chunk_split(base64_encode($data));
$message .= "Content-Type: {\"application/octet-stream\"};\n";
$message .= " name=\"$file\"\n";
$message .= "Content-Disposition: attachment;\n";
$message .= " filename=\"$file\"\n";
$message .= "Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";
$message .= "--{$mime_boundary}\n";
}
$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 know it's not the answer to your post, but after struggling with this kind of problems in the past, I gave up and used PHPMailer. If you still want to roll your own, you should take a look at its source code.

PHP mailer script error

I have an submit page where client scan submit a fillable PDF form along with a photo, using the attached mailer script. The form uploads to the server correctly, however when it is sent to the client, the PDF is blank.
<?php
// did files get sent
if(isset($_FILES) && (bool) $_FILES) {
// define allowed extensions
$allowedExtensions = array("pdf","doc","docx","gif","jpeg","jpg","png","rtf","txt");
$files = array();
// loop through all the files
foreach($_FILES as $name=>$file) {
// define some variables
$file_name = $file['name'];
$temp_name = $file['tmp_name'];
// check if this file type is allowed
$path_parts = pathinfo($file_name);
$ext = $path_parts['extension'];
if(!in_array($ext,$allowedExtensions)) {
die("extension not allowed");
}
// move this file to the server YOU HAVE TO DO THIS
$server_file = "/home/castmeb1/public_html/uploads/$path_parts[basename]";
move_uploaded_file($temp_name,$server_file);
// add this file to the array of files
array_push($files,$server_file);
}
// define some mail variables
$to = "castmebg#gmail.com";
$from = "castmebg#gmail.com";
$subject ="test attachment";
$msg = "Please see attached";
$headers = "From: $from";
// define our boundary
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
// tell the header about the boundary
$headers .= "\nMIME-Version: 1.0\n";
$headers .= "Content-Type: multipart/mixed;\n";
$headers .= " boundary=\"{$mime_boundary}\"";
// part 1: define the plain text email
$message ="\n\n--{$mime_boundary}\n";
$message .="Content-Type: text/plain; charset=\"iso-8859-1\"\n";
$message .="Content-Transfer-Encoding: 7bit\n\n" . $msg . "\n\n";
$message .= "--{$mime_boundary}\n";
// part 2: loop and define mail attachments
foreach($files as $file) {
$aFile = fopen($file,"rb");
$data = fread($aFile,filesize($file));
fclose($aFile);
$data = chunk_split(base64_encode($data));
$message .= "Content-Type: {\"application/octet-stream\"};\n";
$message .= " name=\"$file\"\n";
$message .= "Content-Disposition: attachment;\n";
$message .= " filename=\"$file\"\n";
$message .= "Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";
$message .= "--{$mime_boundary}\n";
}
// send the email
$ok = mail($to, $subject, $message, $headers);
if ($ok) {
echo "<p>mail sent to $to!</p>";
} else {
echo "<p>mail could not be sent!</p>";
}
die();
}
?>
Thanks,
JB
if(isset($_FILES) && (bool) $_FILES) {
is an invalid test for a successful upload. The $_FILES array is always set, and assuming a file upload ATTEMPT was made, the array will NEVER be empty.
You should check for errors like this:
if ($_FILES['name_of_file_field']['error'] === UPLOAD_ERR_OK) {
... file was successfully uploaded ...
}
The error codes are defined here: http://php.net/manual/en/features.file-upload.errors.php

Categories