Загрузка файла через PHP, измельчение .xls файлов - PullRequest
0 голосов
/ 14 октября 2011

У меня есть кусок кода, который берет загруженный пользователем файл и обрабатывает его. Когда пользователь загружает файл .xls, файл уничтожается. Я подозреваю, что это как-то связано с MIME, но я не слишком много о них знаю. Любая помощь будет оценена.

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

}
?>

1 Ответ

0 голосов
/ 14 октября 2011

На каком этапе файл поврежден? На стороне сервера сразу после загрузки файла или на стороне почтового клиента, когда файл был отправлен по электронной почте?

Вот код, переписанный, чтобы сделать его читаемым / совместимым со стандартами ...

$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 .= '--';
...