Creating unique names for uploaded images
It looks like your code works fine, so these comments are my opinion on how I would handle this if I were in your shoes.

This is a pretty standard requirement. Users upload images, and you want to save them with a filename that is (a) unique, and (b) won't cause you grief down the road with funny characters in the file name.

You also need to handle the case where people upload files with the same name over and over again, without creating duplicates.  For instance, for a certain model of camera the first photo on the "camera roll" might always have the same name. Several people might own the same model of camera. Or, dissatisfied with the results of uploading an image, the user edits it locally and uploads a fresh copy. With the same file name as before.

The simplest solution is to skip all the md5 and uniqid() stuff, and simply add a record to a database which has an auto-increment ID field. You would add the original name of the image to the database (for future reference, tooltip etc), but not the name of the file on disk. Once you get the new ID, you copy/move/rename the image file based on the new ID. This gives you nice short, simple file names.

I think this is tidier than inventing a unique file name before adding the database record. Databases have a built-in unique ID feature, so you can get a unique ID "for free!" with each new record. Why invent your own?

If the name of the image file ends up being used in URL's, so you don't want it to be easily guessable, then you want to mess up the file name to make it more complicated. If this is the case, you are better off placing the files where they are not accessible directly via URL.

If you, as an administrator, want to be able to browse through the image files and have the names make sense, or if you want the image names to appear in the URL to assist visitors or for SEO or Google Image search benefits, then you may want to name the images like blog post titles, i.e. simple lower-case-hyphen-separated words with a unique ID on the end. There is lots of code around that will do that for you. (I've got code if you can't find it elsewhere).