Retrieving a file name to attach to an email with SwiftMailer and PHP

旧时模样 提交于 2019-12-01 04:16:47

问题


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

This is the file attaching portion:

//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:

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.

Thank you!


回答1:


Use:

$attachment = Swift_Attachment::fromPath($target_path);

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



来源:https://stackoverflow.com/questions/3290966/retrieving-a-file-name-to-attach-to-an-email-with-swiftmailer-and-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!