a issue with attachment form - php

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.

Related

Trying to send attachments with PHP mail()

I'm trying to store an uploaded file from a form to the uploads folder as well as send the file as an attachment to an email. The email sends perfectly fine and there is also an attachment, however the attachment is unreadable/corrupted.
I have tried with multiple file types and that makes no difference, I still have the same errors.
<?php
//Store File
if (!empty($_FILES) && isset($_FILES['upload'])) {
switch ($_FILES['upload']["error"]) {
case UPLOAD_ERR_OK:
$target = "uploads/";
$target = $target . basename($_FILES['upload']['name']);
if (move_uploaded_file($_FILES['upload']['tmp_name'], $target)) {
$status = "The file " . basename($_FILES['upload']['name']) . " has been uploaded";
$imageFileType = pathinfo($target, PATHINFO_EXTENSION);
} else {
$status = "Sorry, there was a problem uploading your file.";
}
break;
}
echo "Status: {$status}<br/>\r\n";
}
$fileatt = getcwd() . "/uploads"; // Path to the file
$fileatt_type = "application/pdf"; // File Type
$fileatt_name = $_FILES['upload']['name']; // Filename that will be used for the file as the attachment
$email_from = $_POST['email']; // Who the email is from
$email_subject = "Your attached file"; // The Subject of the email
$email_message = "Thanks for visiting mysite.com! Here is your free file.";
$email_message .= "Thanks for visiting."; // Message that the email has in it
$email_to = 'test#test.com'; // Who the email is to
$headers = "From: " . $email_from;
$file = fopen($fileatt . "/" . $fileatt_name, 'rb');
$data = fread($file, filesize($fileatt . "/" . $fileatt_name));
fclose($file);
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
$headers .= "\r\nMIME-Version: 1.0\r\n" . "Content-Type: multipart/mixed;\r\n" . " boundary=\"{$mime_boundary}\"";
$email_message .= "This is a multi-part message in MIME format.\r\n\r\n" . "--{$mime_boundary}\r\n" . "Content-Type:text/html; charset=\"iso-8859-1\"\r\n" . "Content-Transfer-Encoding: 7bit\r\n\r\n" . $email_message .= $_POST['email'] . "<br>" . $_POST['firstname'] . "<br>" . $_POST['surname'] . "<br>" . $_POST['degree'] . "<br>" . "\r\n\r\n";
$data = chunk_split(base64_encode($data));
$email_message .= "--{$mime_boundary}\r\n" . "Content-Type: {$fileatt_type};\r\n" . " name=\"{$fileatt_name}\"\r\n" . "Content-Disposition: attachment;\r\n" . " filename=\"{$fileatt_name}\"\r\n" . "Content-Transfer-Encoding: base64\r\n\r\n" . $data .= "\r\n\r\n" . "--{$mime_boundary}--\r\n";
$ok = mail($email_to, $email_subject, $email_message, $headers);
if ($ok) {
echo "You file has been sent
to the email address you specified.
Make sure to check your junk mail!
Click here to return to mysite.com.";
} else {
die("Sorry but the email could not be sent. Please go back and try again!");
}
?>
Please could somebody point me in the right direction?
You can find the solution here.
Explained completely to need to ass same info again.
Solution

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

attachment is not working in mail function wordpress

Text mail works fine but I want to attach file too.
Attachment is not working.
My code is:
<form method="post" enctype="multipart/form-data">
<input name="filepc" type="file" id="filepc" class="listEm" />
</form>
if (isset($_POST['submit'])) {
$attachments = '';
if (!empty($_FILES['filepc']['tmp_name'])) {
$attachments = array($_FILES['filepc']['name']);
}
headers = "From:" . $your_email . " < " . $email . ">" . "\r\n";
$headers .= "Reply - To:" . $ct_email . "\r\n";
$headers .= "Content-Disposition: attachment; filename=\"".$attachments."\"\r\n\r\n";
//$headers = "Bcc: someone#domain . com" . "\r\n";
$headers = "X - Mailer: PHP / " . phpversion();
mail($to , $subject , $msg , $headers,$attachments);
$successMsg = '<h5 style="color:red;">Sent successfully</h5>';
// }
}
Above code works but file is not attached. Please help me find the solution for this problem.
if(!empty($_FILES['resume']['name'])) {
$mime_boundary="==Multipart_Boundary_x".md5(mt_rand())."x";
$tmp_name = $_FILES['resume']['tmp_name'];
$type = $_FILES['resume']['type'];
$file_name = $_FILES['resume']['name'];
$size = $_FILES['resume']['size'];
// Check to make sure that it is an uploaded file and not a system file
if(is_uploaded_file($tmp_name)){
// Now Open the file for a binary read
$file = fopen($tmp_name,'rb');
// Now read the file content into a variable
$data = fread($file,filesize($tmp_name));
// close the file
fclose($file);
// Now we need to encode it and split it into acceptable length lines
$data = chunk_split(base64_encode($data));
}
$mybody = "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" .
$mybody . "\n\n";
$headers = "From: $from\r\n" .
"MIME-Version: 1.0\r\n" .
"Content-Type: multipart/mixed;\r\n" .
" boundary=\"{$mime_boundary}\"";
$mybody .= "--{$mime_boundary}\n" .
"Content-Type: {$type};\n" .
" name=\"{$file_name}\"\n" .
//"Content-Disposition: attachment;\n" .
//" filename=\"{$fileatt_name}\"\n" .
"Content-Transfer-Encoding: base64\n\n" .
$data . "\n\n" .
"--{$mime_boundary}--\n";
$bodys .= "$mybody <br>";
$subject = "Attachment";
$body = $body . $bodys;
mail($to, $subject, $body, $headers);
}

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?

Uploading File via PHP shredding .xls files

I have a chunk of code that is taking a user uploaded file, and processing it. When the user uploads a .xls file, the file is shredded. I suspect it has something to do with the MIME but I don't know too much about them. Any help would be appreciated.
<?php include ("header1.html") ?>
<!--- End --->
<tr height="100%">
<td align="center" valign="top" style="background-image: url('images/midbg.jpg'); background-repeat:repeat-x; padding-top: 25px; " bgcolor="#e6e6e6" >
<!--- Body begins here --->
<table width="725" border="0" cellspacing="0" cellpadding="2">
<tr>
<td width="100%" valign="top">
<table style="margin-left:130px; margin-top:20px;">
<tr><td>
<p><strong style="font-size:12px"> </strong> </p>
<?php
$userName = $session->userName;
if ($handle = opendir('fileuploads/'.$userName)) {
//echo "Directory handle: $handle\n";
// echo "Files:\n";
$path = 'fileuploads/'.$userName.'/';
/* This is the correct way to loop over the directory. */
while (false !== ($file = readdir($handle))) {
if(($file != "Thumbs.db") && ($file != ".")&& ($file != ".."))
{
$attachment[] = $path.$file;
}
}
// echo '<p><b>Current total = '.$totalsize.'K</b></p>';
closedir($handle);
}
function fileName($inputfile,$userName)
{
$separator = '/'.$userName.'/';
$output = split ($separator, $inputfile);
return $output[1];
}
$files = $attachment;
//print_r($files);
// email fields: to, from, subject, and so on
$memberEmails = $_POST['emails'];
$bcc = $_POST['bccAddress'];
if ($bcc != '')
{
$bcc = $memberEmails . ',' . $bcc;
}
else
{
$bcc = $memberEmails;
}
$to = $_POST['toAddress'];
if($to != '')
{
$to = $userName. "#place.com,". $to;
}
else
{
$to = $userName. "#place.com";
}
$cc = $_POST['ccAddress'];
$from = $userName. "#place.com";
$subject =$_POST['subject'];
$message = $_POST['content'];
$message = str_replace('\"', '"',$message);
$headers = "From: ".$_SESSION['fullName']. "<$from>\n";
// boundary
$semi_rand = md5(time());
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
// headers for attachment
if ($cc != '')
{
$headers .= "CC: ". $cc ."\n";
}
if ($bcc != '')
{
$headers .= "BCC: ". $bcc ."\n";
}
$headers .= "MIME-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";
if( count($files) > 0)
{
$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);
$fileName= fileName($files[$x],$userName);
$data = chunk_split(base64_encode($data));
$message .= "Content-Type: {\"application/octet-stream\"};\n" . " name=\"$files[$x]\"\n" .
"Content-Disposition: attachment;\n" . " filename=\"$fileName\"\n" .
"Content-Transfer-Encoding: base64\n\n" . $data . "\n\n";
$y = $x +1;
if ( count($files) > $y)
{
$message .= "--{$mime_boundary}\n";
}
}
$ok = #mail($to, $subject, $message, $headers);
if ($ok)
{
$logFile = "log/tmlog.log";
$logHandle = fopen($logFile, 'a');
$logData = "[" . date('Y-m-d H:i:s') . "] " .$userName. " - message sent successfully (". $to. ",".$bcc .",". $cc.")\n";
fwrite($logHandle, $logData);
fclose($logHandle);
echo '<META HTTP-EQUIV="Refresh" CONTENT="0;URL=fileuploads/sendRm.php?msg=sent">';
}
else
{
$logFile = "log/tmlog.log";
$logHandle = fopen($logFile, 'a');
$logData = "[" . date('Y-m-d H:i:s') . "] " .$userName. " - message failed\n";
fwrite($logHandle, $logData);
fclose($logHandle);
echo '<META HTTP-EQUIV="Refresh" CONTENT="0;URL=fileuploads/sendRm.php?msg=fail">';
}
}
?>
At what stage is the file damaged? At the server side immediately after the file upload, or at the email client end when the file has been emailed?
Here is the code rewritten to make it readable/standards compliant...
$mime_boundary = "==Multipart_Boundary_x{$semi_rand}x";
// headers for attachment
if ($cc != '') $headers .= "Cc: $cc\r\n";
if ($bcc != '') $headers .= "Bcc: $bcc\r\n";
$headers .= "MIME-Version: 1.0\r\n"
. "Content-Type: multipart/mixed; boundary=\"$mime_boundary\"\r\n";
// multipart boundary
$message = "This is a multi-part message in MIME format.\r\n"
. "--$mime_boundary\r\n"
. "Content-Type: text/html; charset=\"iso-8859-1\"\r\n"
. "Content-Transfer-Encoding: 7bit\r\n"
. "\r\n"
. $message . "\r\n"
. "--$mime_boundary";
if (count($files)) { // Add attachments
for ($x = 0; $x < count($files); $x++){
$data = chunk_split(base64_encode(file_get_contents($files[$x])));
$fileName = fileName($files[$x], $userName);
$message .= "\r\n"
. "Content-Type: application/octet-stream\r\n"
. "Content-Disposition: attachment; filename=\"$fileName\"\r\n"
. "Content-Transfer-Encoding: base64\r\n"
. "\r\n"
. $data . "\r\n"
. "--$mime_boundary";
}
}
$message .= '--';

Categories