简单的 PHP 表单:电子邮件附件(代码高尔夫)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/826265/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Simple PHP form: Attachment to email (code golf)
提问by Adam Davis
Imagine a user that would like to put a form on their website that would allow a website visitor to upload a file and a simple message, which will immediately be emailed (ie, the file is not stored on the server, or if it is then only temporarily) as a file attachment with the note in the message body.
想象一下,一个用户想要在他们的网站上放置一个表单,允许网站访问者上传一个文件和一条简单的消息,该消息将立即通过电子邮件发送(即,该文件未存储在服务器上,或者如果仅暂时)作为文件附件,邮件正文中带有注释。
See more details at http://a2zsollution.com/php-secure-e-mail/
在http://a2zsollution.com/php-secure-e-mail/查看更多详细信息
What is the simplest way to accomplish this?
实现这一目标的最简单方法是什么?
Simplest in terms of:
最简单的方面:
- Size (code golf)
- Ease of implementation (ideally all in one file, needs few to no external resources)
- Not obfuscated for the sake of obfuscation (tradeoffs for size are fine)
- Self contained example (if called without a form post, it displays the form)
- 尺寸(码高尔夫)
- 易于实施(理想情况下全部在一个文件中,几乎不需要外部资源)
- 为了混淆而不是混淆(大小的权衡很好)
- 自包含示例(如果在没有表单发布的情况下调用,则显示表单)
This is nearly the reverse of: How to get email and their attachments from PHP. It almost could have been answered in Compiling email with multiple attachments in PHP, but it doesn't actually show code.
这几乎与以下内容相反:如何从 PHP 获取电子邮件及其附件。它几乎可以在Compiling email with multiple attachments in PHP 中得到回答,但它实际上并没有显示代码。
回答by MalphasWats
Just for fun I thought I'd knock it up. It ended up being trickier than I thought because I went in not fully understanding how the boundary part works, eventually I worked out that the starting and ending '--' were significant and off it went.
只是为了好玩,我想我会把它敲掉。结果比我想象的要棘手,因为我没有完全理解边界部分是如何工作的,最终我发现开始和结束的 '--' 很重要,然后就没有了。
<?php
if(isset($_POST['submit']))
{
//The form has been submitted, prep a nice thank you message
$output = '<h1>Thanks for your file and message!</h1>';
//Set the form flag to no display (cheap way!)
$flags = 'style="display:none;"';
//Deal with the email
$to = '[email protected]';
$subject = 'a file for you';
$message = strip_tags($_POST['message']);
$attachment = chunk_split(base64_encode(file_get_contents($_FILES['file']['tmp_name'])));
$filename = $_FILES['file']['name'];
$boundary =md5(date('r', time()));
$headers = "From: [email protected]\r\nReply-To: [email protected]";
$headers .= "\r\nMIME-Version: 1.0\r\nContent-Type: multipart/mixed; boundary=\"_1_$boundary\"";
$message="This is a multi-part message in MIME format.
--_1_$boundary
Content-Type: multipart/alternative; boundary=\"_2_$boundary\"
--_2_$boundary
Content-Type: text/plain; charset=\"iso-8859-1\"
Content-Transfer-Encoding: 7bit
$message
--_2_$boundary--
--_1_$boundary
Content-Type: application/octet-stream; name=\"$filename\"
Content-Transfer-Encoding: base64
Content-Disposition: attachment
$attachment
--_1_$boundary--";
mail($to, $subject, $message, $headers);
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>MailFile</title>
</head>
<body>
<?php echo $output; ?>
<form enctype="multipart/form-data" action="<?php echo $_SERVER['PHP_SELF'];?>" method="post" <?php echo $flags;?>>
<p><label for="message">Message</label> <textarea name="message" id="message" cols="20" rows="8"></textarea></p>
<p><label for="file">File</label> <input type="file" name="file" id="file"></p>
<p><input type="submit" name="submit" id="submit" value="send"></p>
</form>
</body>
</html>
Very barebones really, and obviously the using inline CSS to hide the form is a bit cheap and you'd almost certainly want a bit more feedback to the user! Also, I'd probably spend a bit more time working out what the actual Content-Type for the file is, rather than cheating and using application/octet-stream but that part is quite as interesting.
非常准系统,显然使用内联 CSS 隐藏表单有点便宜,而且您几乎肯定希望向用户提供更多反馈!此外,我可能会花更多的时间来确定文件的实际内容类型是什么,而不是欺骗和使用 application/octet-stream,但这部分同样有趣。
回答by Nael El Shawwa
A combination of this http://www.webcheatsheet.com/PHP/send_email_text_html_attachment.php#attachment
这个http://www.webcheatsheet.com/PHP/send_email_text_html_attachment.php#attachment的组合
with the php upload file example would work. In the upload file example instead of using move_uploaded_file to move it from the temporary folder you would just open it:
使用 php 上传文件示例即可。在上传文件示例中,而不是使用 move_uploaded_file 将其从临时文件夹中移动,您只需打开它:
$attachment = chunk_split(base64_encode(file_get_contents($tmp_file)));
where $tmp_file = $_FILES['userfile']['tmp_name'];
在哪里 $tmp_file = $_FILES['userfile']['tmp_name'];
and send it as an attachment like the rest of the example.
并将其作为附件发送,就像示例的其余部分一样。
All in one file / self contained:
全在一个文件/自包含:
<? if(isset($_POST['submit'])){
//process and email
}else{
//display form
}
?>
I think its a quick exercise to get what you need working based on the above two available examples.
我认为这是一个快速练习,可以根据上述两个可用示例获得您需要的工作。
P.S. It needs to get uploaded somewhere before Apache passes it along to PHP to do what it wants with it. That would be your system's temp folder by default unless it was changed in the config file.
PS 它需要先上传到某个地方,然后 Apache 将其传递给 PHP 以执行它想要的操作。默认情况下,这将是您系统的临时文件夹,除非它在配置文件中进行了更改。
回答by Adrian
This article "How to create PHP based email form with file attachment" presents step-by-step instructions how to achieve your requirement.
本文“如何创建带有文件附件的基于 PHP 的电子邮件表单”提供了如何实现您的要求的分步说明。
Quote:
引用:
This article shows you how to create a PHP based email form that supports file attachment. The article will also show you how to validate the type and size of the uploaded file.
本文将向您展示如何创建支持文件附件的基于 PHP 的电子邮件表单。本文还将向您展示如何验证上传文件的类型和大小。
It consists of the following steps:
它由以下步骤组成:
- The HTML form with file upload box
- Getting the uploaded file in the PHP script
- Validating the size and extension of the uploaded file
- Copy the uploaded file
- Sending the Email
- 带有文件上传框的 HTML 表单
- 在 PHP 脚本中获取上传的文件
- 验证上传文件的大小和扩展名
- 复制上传的文件
- 发送电子邮件
The entire example code can be downloaded here
整个示例代码可以在这里下载
回答by mcrumley
I haven't tested the email part of this (my test box does not send email) but I think it will work.
我还没有测试过这个的电子邮件部分(我的测试盒不发送电子邮件),但我认为它会起作用。
<?php
if ($_POST) {
$s = md5(rand());
mail('[email protected]', 'attachment', "--$s
{$_POST['m']}
--$s
Content-Type: application/octet-stream; name=\"f\"
Content-Transfer-Encoding: base64
Content-Disposition: attachment
".chunk_split(base64_encode(join(file($_FILES['f']['tmp_name']))))."
--$s--", "MIME-Version: 1.0\r\nContent-Type: multipart/mixed; boundary=\"$s\"");
exit;
}
?>
<form method="post" enctype="multipart/form-data" action="<?php echo $_SERVER['PHP_SELF'] ?>">
<textarea name="m"></textarea><br>
<input type="file" name="f"/><br>
<input type="submit">
</form>
回答by Moot
In order to add the file to the email as an attachment, it willneed to be stored on the server briefly. It's trivial, though, to place it in a tmp location then delete it after you're done with it.
为了将文件添加到电子邮件作为附件,这将需要存储在服务器上简要介绍。但是,将它放在 tmp 位置然后在完成后将其删除是微不足道的。
As for emailing, Zend Mailhas a very easy to use interface for dealing with email attachments. We run with the whole Zend Framework installed, but I'm pretty sure you could just install the Zend_Mail library without needing any other modules for dependencies.
至于电子邮件,Zend Mail有一个非常易于使用的界面来处理电子邮件附件。我们在安装了整个 Zend 框架的情况下运行,但我很确定您可以只安装 Zend_Mail 库,而无需任何其他依赖模块。
With Zend_Mail, sending an email with an attachment is as simple as:
使用 Zend_Mail,发送带有附件的电子邮件非常简单:
$mail = new Zend_Mail();
$mail->setSubject("My Email with Attachment");
$mail->addTo("[email protected]");
$mail->setBodyText("Look at the attachment");
$attachment = $mail->createAttachment(file_get_contents('/path/to/file'));
$mail->send();
If you're looking for a one-file-package to do the whole form/email/attachment thing, I haven't seen one. But the individual components are certainly available and easy to assemble. Trickiest thing of the whole bunch is the email attachment, which the above recommendation makes very simple.
如果您正在寻找一个文件包来完成整个表单/电子邮件/附件的工作,我还没有看到过。但是各个组件肯定是可用的并且易于组装。最棘手的是电子邮件附件,上面的建议非常简单。
回答by Kevin Peno
PEAR::Mail_Mime? Sure, PEAR dependency of (min) 2 files (just mail_mime itself if you edit it to remove the pear dependencies), but it works well. Additionally, most servers have PEAR installed to some extent, and in the best cases they have Pear/Mail and Pear/Mail_Mime. Something that cannot be said for most other libraries offering the same functionality.
PEAR::Mail_Mime? 当然,(最小)2 个文件的 PEAR 依赖项(如果您编辑它以删除 pear 依赖项,则只是 mail_mime 本身),但它运行良好。此外,大多数服务器都在某种程度上安装了 PEAR,在最好的情况下,它们安装了 Pear/Mail 和 Pear/Mail_Mime。对于提供相同功能的大多数其他库来说,这是无法说的。
You may also consider looking in to PHP's IMAP extension. It's a little more complicated, and requires more setup (not enabled or installed by default), but is must more efficient at compilng and sending messages to an IMAP capable server.
您也可以考虑查看 PHP 的IMAP 扩展。它有点复杂,需要更多设置(默认情况下未启用或安装),但必须更有效地编译和发送消息到支持 IMAP 的服务器。

