Reputation: 947
I have a foreach loop that is processing image uploads. When I add multiple images they are given a filename that consists of a unique id and a time stamp using $filebase = uniqid() . '_' . time();
When the images are processed they have the same image name, and I don't understand why the foreach loop isn't giving unique file names?
I have the $temp
variable assigned to the index of the foreach loop with the following line: $temp = $_FILES['standard-upload-files']['tmp_name'][$index];
so I don't understand why it doesn't increment a new value?
The images are being moved correctly to the destination folder (albeit with the same name) so I know it isn't an issue with my HTML form, or the initial foreach loop.
if(isset($_POST['submit-images'])) {
foreach($_FILES['standard-upload-files']['name'] as $index => $filename ) {
if($_FILES['standard-upload-files']['error'][$index] === 0 ) {
$temp = $_FILES['standard-upload-files']['tmp_name'][$index];
$filebase = uniqid() . '_' . time();
move_uploaded_file($temp, "images-download/{$filebase}");
}
} // main foreach
} // isset($_POST)
Upvotes: 0
Views: 402
Reputation: 715
I see, my first guess is using uniqid. Uniqid
is generated based on the current time in microseconds which could result in the same values. As the documentation mentions, this function does not guarantee the uniqueness of the return value.
Since most systems adjust the system clock by NTP or like, system time is changed constantly. Therefore, it is possible that this function does not return a unique ID for the process/thread. Use more_entropy
to increase the likelihood of uniqueness.
A [not so reliable] solution would be setting the more_entropy
to true:
uniqid('', true)
but again, remember this approach is not reliable.
So use another method for generating your unique IDs (UUID
for example as explained in the comments here.)
Upvotes: 1