Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a symfony value for /tmp (or other similar folder location)?

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?

like image 675
Patrick Avatar asked Jan 03 '23 16:01

Patrick


1 Answers

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.

like image 193
Yanis-git Avatar answered Jan 05 '23 10:01

Yanis-git