Lugi's avatar
Level 21

Bulk File Uploads - unique names

Hi, I'm building the post images upload feature for my site using Dropzone (the same way as in https://laracasts.com/series/build-project-flyer-with-me/episodes/11).

I don't trust users' filenames so I would like to create a unique name for each uploaded image.

I tried to combine $post->id with time() or Carbon but it seems that the timestamps are the same for all images uploaded at the same time.

I would like to hear what methods do you use to generate unique image names ?

Perfect names would use post title (but sometimes titles could be very long - wondering if this could be a problem ?) and number (how to figure out the number if multiple files are uploading at the same time, using a static variable or something..?):

post-title-1.jpg
post-title-2.jpg
post-title-3.jpg
another-post-title-1.jpg
another-post-title-2.jpg
0 likes
2 replies
ohffs's avatar
ohffs
Best Answer
Level 50

Do you need the resulting files to keep a human readable name? If not you could just use a hash (or even str_random). If you do then maybe use a short hash + the sanitised filename + microtime?

1 like
Lugi's avatar
Level 21

@ohffs Thanks for your answer. Based on your idea, I did it like this:

$image_slug = str_limit($post->title, 30);
$image_slug = str_slug($image_slug, '-');
$final_name = $post->id . '-' . $image_slug . '-' . str_random(3) . '.' . $file->getClientOriginalExtension();
1 like

Please or to participate in this conversation.