我正在尝试通过php邮件功能将文件作为附件发送。我的代码是发送文件,但它显示的大小为0KB。我已经谷歌了但是没有找到解决方案。请帮帮我。
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);
?>
我认为我在这部分做错了,但我不确定。
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";
}
由于
答案 0 :(得分:1)
您正在尝试打开$_FILES['file']['name']
,但name
字段包含原始文件的名称,而不是服务器上文件的路径。要访问服务器上的文件,请使用
$_FILES['file']['tmp_name']
另外,为了确保文件正确上传,请使用
$_FILES['file']['error'] == UPLOAD_ERR_OK