Im writing my first online shop in PHP. Now working on “add product” form and im not sure know how to store images.
I think i should:
- check is this image or not
- resize image to “standard” dimensions used in my shop and generate thumbnail
- generate unique filename and store image in “images” directory
- save image with unique filename and insert row into my Images table
I created table with columns like this:
- Id
- Location – url of image – “/0953026326323436324.jpg” for example
- OriginalFilename – original name of file that user was uploading – “myproduct1.jpg” for example
Questions:
- Is there any better way to do this?
- Shall i use Id from Images table as unique filename, or shall i stay with generating unique name (by using PHP function)?
- Shall i generate md5 hash and store it in Images table to avoid/handle duplicates?
Edit 2012-03-03:
By duplicates I mean files with identical content (but maybe diffrent name).
Im not using any framework, that will be simple and lightweight online-shop.
It really depends on what your application does with those images. These are some of the things I learnt by experience…
How many images?
If we are talking about thousands of images, keep in mind that a folder with that amount of files is probably not accesible via FTP. You can classify them and put them in different subfolders if you need access to them.
Classification can be done by a number of things… from size to odd/even ID numbers. It all depends on how much you need to split them up.
Are they private images? Should they be publicly accesed? If you use just the ID as unique identifier, it’s pretty easy to guess and find other images, since they are most likely auto-incremental. You can generate a more secure name in those cases just throwing user IDs, timestamps, random numbers, a hash, or whatever combination…
Hashing the names? You don’t get any extra security off of this. If you are already using a combination of things of the names, hashing it is just an extra thing to do. Say you are using [image_id]_[timestamp] for the names, if you hash it, you lose that information. You do have it in your database, but it’s also good having it in the file names. If for some reason, you need to delete certain files it would be easier if you could recognize them. And, going back to the amount of images you may have… there could be collitions in the MD5. Meaning 2 files would get the same name.. (It’s really rare, but it could happen)
Since it’s a store, I’m guessing you don’t need the extra security on the image names, but you might need the extra classification.
Btw, according to your step by step, you can’t use the ID of the image for the filename because you insert the row into the table AFTER saving the image.
If you need more details, do leave a comment.