开发者

How to name upload images from users?

I was wondering how should I name my images upload using PHP & MySQL, should I use the auto increment number as the name of the image for example, 1.gif or should I use some random numbers or something. I was thinking auto increment was better. Bu开发者_如何学运维t what would be best?


Since no one's officially offered this yet, I'd advise to simply store the file name as the database unique id, nothing more, and store the extension in the database (unless you are forcing all images to be .jpg or something, then you don't need to).

  • It is always going to be a safe file name (an integer)
  • It will always be unique
  • No need to store the file name in the db or worry about scrubbing it.
  • It will be as small as possible.

Why I would not use the user's username/id, as suggested by others:

  • There's no benefit, and no reason to expose a user's id in the file name if you don't need to.
  • No need to scrub it for allowed characters, which may even end up with multiple users with the same "file safe" user name.
  • User names may change, so it doesn't always make sense, and you don't want to have to rename files if you want them to match.

Why I would not use the original file name in any form:

  • There's no benefit.
  • You have to scrub it for allowed characters.
  • There will be duplicates.

Unless you are interested in vanity file names, I can't think of any reason not to just use the auto-increment id. If your DB ids are unique, your file names will be too.

If later on you do want "pretty" file names, you can use .htaccess to rewrite the requests, and/or output your images through a php script, which also has the benefit of checking for permissions and whatnot if you need it.


What about

md5(microtime()) 

?

It is pretty unique


I like to use a combination of an auto incrementing id and filename.

So if I upload the image my_photo.jpg and it gets stored with an id of 5, I would save it as 5_my_photo.jpg

This way, the original filename and extension are preserved and I can deliver it back to the user without the id prefix if I want to.


One good way to name the images is to append a user name to an autoincrement value padded on the left with zero, such as "00000027MyPic.jpg".


if you are worried about the image being unique, store it as time().$extention.

I also prefer to put the user's username as a prefix, but thats just me, there is no reason to do that.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜