Unique identifier for filenames
dev opened this issue · comments
Kenny commented
Hi,
Is it possible to add a unique identifier to filenames when trying to save them?
If someone sent me "image.jpeg", and I get a new email with "image.jpeg", the old image.jpeg would be overwritten.
This is my code:
$name = $attachment->getFileName();
$data = $attachment->getData();
$mime = $attachment->getMimeType();
$size = $attachment->getSize();
$saved = $attachment->saveToDirectory($path);
I would like it to be for example: image37ad2d8e.jpeg
narvinwilliams commented
Here's a quick solution, some of these codes can be merged together. However, I wrote it out for simplicity when reading.
// Information about the file and where to save it
$saveToDirectory = getcwd() . "\\attachments\\"; // Get's the current directory and folder attachments
$attachmentName = $attachment->getFileName();
$pathToSave = $saveToDirectory . $attachmentName;
$attachment->saveToDirectory($saveToDirectory); // Save the file here
// Renaming the file to a unqiue id name
$fileExt = (new SplFileInfo($fileName))->getExtension(); // Get the file extention
$newFileName = uniqid() . "." . $fileExt; // Create a name for the file
$renameFilePath = $tmpdir . $newFileName;// Path to save the file
rename($pathToSave, $renameFilePath);