使用 SwiftMailer 和 PHP 检索要附加到电子邮件的文件名 [英] Retrieving a file name to attach to an email with SwiftMailer and PHP
问题描述
我昨天问了这个问题并得到了一个建议,并使用了它,但由于某种原因它不起作用.因此,我需要检索用户从 HTML 表单上传到我的服务器的文件的名称.我需要将此文件附加到由 PHP/SwiftMailer 发送的电子邮件中.这是我的代码,文件上传部分:
I asked the question yesterday and got an advice, and used it, but it doesn't work for some reason. So, I need to retrieve the name of the file that was uploaded to my server from an HTML form by a user. I need this file to be attached to an email that is to be sent by PHP/SwiftMailer. Here is my code, the file upload portion:
//File upload
// Where the file is going to be placed
$target_path = "uploads/";
// Add the original filename to our target path.
//Result is "uploads/filename.extension"
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
echo "The file ". basename( $_FILES['uploadedfile']['name']).
" has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";
}
//End of file upload
这是文件附加部分:
//Create the attachment
$attachment = Swift_Attachment::fromPath($_FILES['uploadedfile']['tmp_name']);
为什么不从服务器获取文件?这是错误消息,看起来它试图在错误的目录中查找文件:
Why doesn't it get the file from the server? Here is the error message, and it looks like it's trying to find the file in a wrong directory:
警告:fopen(/tmp/phpHJdw0H)[function.fopen]:打开失败流:没有这样的文件或目录/home/myserver/mydomain.com/Hawaii/html/swift-mailer/lib/classes/Swift/ByteStream/FileByteStream.php在第 131 行致命错误:在/home/myserver/mydomain.com/Hawaii/html/swift-mailer/lib/classes/Swift/ByteStream/中出现消息无法打开文件以读取 [/tmp/phpHJdw0H]"的未捕获异常Swift_IoException"FileByteStream.php:133 堆栈跟踪:#0
等
Warning: fopen(/tmp/phpHJdw0H) [function.fopen]: failed to open stream: No such file or directory in /home/myserver/mydomain.com/Hawaii/html/swift-mailer/lib/classes/Swift/ByteStream/FileByteStream.php on line 131 Fatal error: Uncaught exception 'Swift_IoException' with message 'Unable to open file for reading [/tmp/phpHJdw0H]' in /home/myserver/mydomain.com/Hawaii/html/swift-mailer/lib/classes/Swift/ByteStream/FileByteStream.php:133 Stack trace: #0
etc.
谢谢!
推荐答案
使用:
$attachment = Swift_Attachment::fromPath($target_path);
这是因为您已将文件从其临时位置移动,$_FILES['uploadedfile']['tmp_name']
返回您使用 move_uploaded_file.这假设 $target_path
在 swift 邮件程序代码的范围内
This is because you have moved the file from its temporary location, $_FILES['uploadedfile']['tmp_name']
returns the path from before you moved the file using move_uploaded_file. This assumes the $target_path
is within scope to the swift mailer code
这篇关于使用 SwiftMailer 和 PHP 检索要附加到电子邮件的文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!