用php发送附件

I am trying to create an email form that allows you to send an attachment. I have pieced code together from my PHP book and several websites.

When I send the email using this form the attachment ends up corrupted and the "$comments" don't seem to go through.

Here is the code I am using:

<?php
$to = $_POST['to'];
$from = $_POST['from'];
$re = $_POST['re'];
$comments= $_POST['comments'];

$att = $_FILES['att'];
$att_path= $_FILES['att']['tmp_name'];
$att_name = $_FILES['att']['name'];
$att_size = $_FILES['att']['size'];
$att_type = $_FILES['att']['type'];

//open, read, then close the file
$fp = fopen( $att_path, "rb" );
$file = fread( $fp, $att_size );
fclose($fp);

#create a boundary string
$num = md5(time());
$str = "==Multipart_Boumdary_x{$num}x";

//encode the data for transit
$file = chunk_split(base64_encode($file));

//define header
$hdr = "MIME-Versio: 1.0
";
$hdr .= "Content-Type: multipart/mixed; ";
$hdr .= "boundary=\"{$str}\"
";
$hdr .= "From: $from 
";

#define message
$msg = "This is a multi-part message in MIME format

";
$msg .= "--{$str}
";
$msg .= "Content-Type: text/plain; charset=\"iso-8859-1\"
";
$msg .= "Content-Transfer-Encoding: 8bit
";
$msg .= "$comments

";
$msg .= "--{$str}
";

#define the non-text attatchment
$msg .= "Content-Type: {$att_type}; ";
$msg .= "name=\"{$att_name}\"
";
$msg .= "Content-Disposition: attachment; ";
$msh .= "filename=\"{$att_name}\"
";
$msg .= "Content-Transfer-Encoding: base64
";
$msg .= "$file

";
$msg .= "--{$str}";

#sendmail
$ok = mail( $to, $re, $msg, $hdr );
if( $ok ) echo "OK";

?>

So, what am I doing wrong?

Thanks!

Try this to encode your file for transit.

Replace the line:

  $file = chunk_split(base64_encode($file));

With:

  //Encode the file for transit
  $content = '';
  $fp = fopen($att_path, 'r'); 
  do { 
    $data = fread($fp, 8192); 
    if (strlen($data) == 0) break; 
    $content .= $data; 
  } while (true); 
  $file = chunk_split(base64_encode($content)); 

I think you'd find it easier to use a something like PHPMailer http://phpmailer.worxware.com/index.php?pg=phpmailer

$str = "==Multipart_Boumdary_x{$num}x";

Hopefully you've tried (notice the spelling of bouNdary):

$str = "==Multipart_Boundary_x{$num}x";