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

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?

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);
...

Attachment in PHP showing 0KB

I am trying to send files as attachment through php mail function. My code is sending the files but it is showing size 0KB. I already google it but didn't found a solution. Please help me.
HTML:
<form method="post" action="code.php" enctype="multipart/form-data">
<input type="file" name="file[]" multiple="multiple" />
<button type="submit">Submit</button>
</form>
PHP:
<?php
foreach ($_FILES['file']['name'] as $filename){
$files[] = $filename; // create array of terms
}
// email fields: to, from, subject, and so on
$to = "receiver_email_here";
$from = "sender_email_here";
$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";
}
mail($to, $subject, $message, $headers);
?>
I think I am doing something wrong in this part but I am not sure.
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";
}
Thanks
You are trying to open $_FILES['file']['name'], but the name field contains the name of the original file, not the path to the file on the server. To access the file on the server, use
$_FILES['file']['tmp_name']
Also to make sure that the file was uploaded correctly, use
$_FILES['file']['error'] == UPLOAD_ERR_OK

PHP Form Upload - Extension invalid when file left blank

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

how to attach multiple files from form to mail in php?

I am trying to attach two files at maximum, to send them by mail, but the files are sent by mail as binary code, so when I open the received mail I found the files as binary, here is my code:
$files = array();
if(is_uploaded_file($_FILES['cv']['tmp_name']))
array_push($files, $_FILES['cv']);
if(is_uploaded_file($_FILES['portfolio']['tmp_name']))
array_push($files, $_FILES['portfolio']);
$subject = "Contact Mail";
$headers = 'From: '.$email_fromto."\r\n".
"subject: {$subject}";
$randomVal = md5(time());
$mimeBoundary = "==Multipart_Boundary_x{$randomVal}x";
$headers .= "\nMIME-Version: 1.0\n";
$headers .= "Content-Type: multipart/mixed;\n" ;
$headers .= " boundary=\"{$mimeBoundary}\"";
$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" .
"From: $sex $fname $lname.\r\n".
"Message: {$message}";
$email_fromto = "mail#mail.com";
foreach($files as $userfile){
$tmpName = $userfile['tmp_name'];
$fileType = $userfile['type'];
$fileName = $userfile['name'];
if(file($tmpName)){
$file = fopen($tmpName,'rb');
$data = fread($file,filesize($tmpName));
fclose($file);
$data = chunk_split(base64_encode($data));
$message .= "--{$mimeBoundary}\n" .
"Content-Type: {$fileType};\n" .
" name=\"{$fileName}\"\n" .
"Content-Transfer-Encoding: base64\n\n" .
$data . "\n\n" .
"--{$mimeBoundary}--\n";
}
}
so where is the error in what I did?
use like this
// 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"
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 "Mail was Send Sucessfully";
else
echo "Failed to send";

a issue with attachment form

the following code works just fine, but when users submitting without any attachments the page gives error alert and nothing is happened, ther mast any condition that i'm missing, someone knows what i need to add?
<?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, array('temp_name' => $temp_name, 'file_name' => $file_name));
}
// email fields: to, from, subject, and so on
$to = "dorozenman#gmail.com";
$from = $_POST['sender_email'];
$subject ="בקשה להצעת עבודה מ" . $_POST['sender_name'] .' '. $_POST['sender_suname'];
$message = 'שם: '. $_POST['sender_name'] . "\r\n" . 'שם משפחה: ' . $_POST['sender_suname'] . "\r\n" . 'תאריך לידה: ' . $_POST['sender_Bday'] . "\r\n" . 'עיסוק נוכחי: ' . $_POST['sender_work'] . "\r\n" . 'טלפון: ' . $_POST['sender_phone'] . "\r\n" . 'מייל: ' . $_POST['sender_email'] . "\r\n" . 'טקסט חופשי: ' . $_POST['sender_way'] ;
$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++){
$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";
}
// send
$ok = #mail($to, $subject, $message, $headers);
if ($ok) { ?>
<script language="javascript" type="text/javascript">
alert('הבקשה נשלחה! שיהיה לך בהצלחה!');
top.window.location = 'https://www.facebook.com/gingereilat';
</script>
<?php } else { ?>
<script language="javascript" type="text/javascript">
alert('שגיאה במערכת בצעו פעולה זאת מאוחר יותר או צרו קשר dorozenman#gmail.com');
top.window.location = 'https://www.facebook.com/gingereilat';
</script>
<?php
}
}
?>
your whole code in following if clause
if(isset($_FILES) && (bool) $_FILES) {
check where its applicable.
Please post the error messages! That makes answering your question a lot easier.
Just reading the code, an obvious problem is var $files is only initialised inside the first if statement, but then you use it in the for loop.
Move the line $files = array(); to the top of your script so it is always initialised as an empty array.

Categories