Don't use timestamps with multi-image uploads.

I'm pretty sure all programmers have had to write code to upload an image at some point, and I'm pretty sure most of you have used a timestamp as the image name. Well...I recently ran into a situation where this is a bad idea, let me explain why.

Don't use timestamps

Let's run through a scenario with some code. Let's take an array of names and concatenate a timestamp onto those names and see what happens.
$names = collect([
        '0' => 'Jonathon',
        '1' => 'Justin',
        '2' => 'Sally',
        '3' => 'Sally',
    ]);

    $testArray = [];

    foreach ($names as $name) {
        $testArray[] = $name . '-' . time();
    }

    dd($testArray);

$results = array:3 [â–¼
  0 => "Jonathon-1636344452"
  1 => "Justin-1636344452"
  2 => "Sally-1636344452"
  3 => "Sally-1636344452"
];
Did you notice all the timestamps are the same. This is because the snippet of code ran so quick that the timestamp never changed, it never had a chance to get to the next time.

I ran into this exact situation recently. I was uploading multiple images at ones, storing them on Amazon S3 and saving the path to the database. When I saved the images I set the file name to time() . '.jpg';, which obviously causes an issue because now I have duplicate files named the same thing and duplicate file paths stored in the database.


Whats the solution?

Well...I'm sure there are a lot of solutions, but the main thing is that on each loop you want to get a unique value each time. So..What I did was used the LaravelStr::random(8) helper function. And this is what we get:
$names = collect([
        '0' => 'Jonathon',
        '1' => 'Justin',
        '2' => 'Sally',
        '3' => 'Sally',
    ]);

    $testArray = [];

    foreach ($names as $name) {
        $testArray[] = $name . '-' . Str::random(8);
    }

    dd($testArray);

$results = array:4 [â–¼
  0 => "Jonathon-SeTNhsmL"
  1 => "Justin-2sjRUxg8"
  2 => "Sally-Laytdn5m"
  3 => "Sally-6cUDA5Cd"
]
As you can see we're now getting a unique value each time. Keep in mind the longer the string, the better your chances of returning only unique values if you have a large dataset.

If you have another solution, comment below. I'd like to hear them!