用php发送附件 [英] Sending an attachment with php

查看:175
本文介绍了用php发送附件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个电子邮件表单,允许您发送附件。我从我的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.

当我使用此表单发送电子邮件时,附件最终损坏,$ comments不会似乎要经历。

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

这是我使用的代码:

<?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\r\n";
$hdr .= "Content-Type: multipart/mixed; ";
$hdr .= "boundary=\"{$str}\"\r\n";
$hdr .= "From: $from \r\n";

#define message
$msg = "This is a multi-part message in MIME format\r\n\n";
$msg .= "--{$str}\r\n";
$msg .= "Content-Type: text/plain; charset=\"iso-8859-1\"\r\n";
$msg .= "Content-Transfer-Encoding: 8bit\r\n";
$msg .= "$comments\r\n\n";
$msg .= "--{$str}\r\n";

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

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

?>

那么我做错了什么?

谢谢!

推荐答案

尝试这样对您的文件进行编码。

Try this to encode your file for transit.

替换行:

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

这篇关于用php发送附件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆