I have a Symfony 3.3 application that is successfully sending an email with an attachment. The relevant function looks like this:
private function sendEmail($data)
{
$vgmsContactMail = self::contactMail;
$mailer = $this->get('mailer');
/* @var $uploadedFile UploadedFile */
$uploadedFile = $data["attachment"];
$extension = $uploadedFile->guessExtension();
if(!in_array($extension, ['pdf','rtf']) ){
die('Please upload a .pdf or .rtf file.');
}
$newFilePath = '/tmp';
$newFileName = 'temporary' . rand(0,10000) . '.rtf';
$uploadedFile->move($newFilePath, $newFileName);
$attachment = \Swift_Attachment::fromPath('/tmp/' . $newFileName);
$message = \Swift_Message::newInstance("VGMS Contact Form: ". $data["subject"])
->setFrom(array($vgmsContactMail => "Message by ".$data["name"]))
->setTo(array(
$vgmsContactMail => $vgmsContactMail
))
->setBody($data["message"]."<br>ContactMail :".$data["email"])
->attach($attachment)
;
return $mailer->send($message);
}
My problem is that hard-coding the /tmp
directory feels very brittle. Is there a more elegant way to get the path to the directory where temporary files are stored?
to know actual tmp folder you can use this function
sys_get_temp_dir();
Source : http://php.net/manual/fr/function.sys-get-temp-dir.php
You can use it like this :
$newFileName = tempnam(sys_get_temp_dir(), 'myAppNamespace');
and you will have full file path with random and uniq name.
Not link to your first question but i have notice little issue on your code :
$newFileName = 'temporary' . rand(0,10000) . '.rtf';
You have hard coded extension type on your code. but your previous check is about pdf/rtf extension.
My solution will fix this issue also.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With