Uploading image ... preventing filename conflicts


I’m writing a PHP program that allows users to upload images. These images are stored in a directory and the URL is saved in a MySQL database.

If I name each image “image_1”, “image_2”, etc. and get the the number by counting how many images have already been stored in the database (or the directory or whatever), could cause errors if two users are uploading a file at the same time? I.e. cause two images to have the same name, which would mean one overwrites the other one?

For example

A begins uploading image…
B begins uploading image…
A counts existing images, result: 0
A’s image named as “image_1.jpg”
B coutns existing images, result: 0
B’s image named as “image_1.jpg”
A’s image saved as “image 1.jpg”
B’s image saved as “image 1.jpg”

I just don’t really know how these syncronisation issues are handled with MySQL and PHP … any ideas? Thanks.

In MySQL: you could use an autoincremental id field (if you have an ‘images’ table).
In PHP: you could add the microtime to the imagename.