lara28580's avatar

Is this collision free?

I have a form where I am uploading images and I want the hash which is generated as the filename for the uploaded image to be collision free. Now I want to know if the way I am doing it is safe.

This is the function which is handling this. The file class is using the Str::random function so not very safe, right?

 protected function uploadFile(UploadedFile|File $logo): ?String
    {
        return Storage::putFile('company/logos', $logo);
    }
0 likes
7 replies
sr57's avatar

@Niush

Good precision but you should put numbers behind 'very low' and minuscule, in order to see that in real life 'very low' is largely enough.

If you want to be 100% unique, you have to test if the name already exists and in that case generate a new one.

sr57's avatar

@SmokeTM

Many different ways

  • generate an "almost unique" name as before , test if this name still exists with file_exists

  • store your filename in db and use a query rather than file exists

  • catch the error and regenerate a new filename in case of error (limited number of time to avoid infinite loop)

  • as I did before using Laravel, use microtime(true) (with rand if some needed some obfuscation) to create your unique file name.

That said, sure you'll get other errors (disk full, inode limit, ...) before needed this..

1 like

Please or to participate in this conversation.