关于为上载的文件生成文件名

Im just uploading files from a form and I'm nor sure about the method to generate the file names..

In which case should I use something like this:

 sha1(uniqid(mt_rand(), true))

and in which should I use just this:

uniqid()

uniqid() is good enough for a file name.

But be aware that neither uniqid() not sha1() will get you absolutely unique strings. So before saving the file to IO, check if a file with that name already exists.

I agree with lukassteiner. They won't give you absolute uniqueness; use the GUID.

You can, very simply, define the GUID function like so:

function getGuid() {

    return strtolower( sprintf('%04X%04X-%04X-%04X-%04X-%04X%04X%04X', 
                        mt_rand(0, 65535), 
                        mt_rand(0, 65535), 
                        mt_rand(0, 65535), 
                        mt_rand(16384, 20479), 
                        mt_rand(32768, 49151), 
                        mt_rand(0, 65535), 
                        mt_rand(0, 65535), 
                        mt_rand(0, 65535)) );

// from the official PHP documentation

}

In my opinion, you're just increasing the runtime (no matter how small) with the sha1 function; you're better off to use the uniqid() function. The documentation, however, does say this:

Warning

This function does not create random nor unpredictable strings. This function must not be used for security purposes. Use a cryptographically secure random function/generator and cryptographically secure hash functions to create unpredictable secure IDs.

So, if you want Cryptographically Secure randoms, you can use:

  • random_int()
  • openssl_random_pseudo_bytes()

I prefer the second one.