php Unique filename when uploading
If you need a unique name, you can use uniqid
.
$filename = uniqid() . '.jpeg';
Be warned though that it will only be unique across one machine, ie it can generate the same thing if you run it at the very same time on two different machines.
The best option IMO would be to to use sha1_file It will create a unique hash based on the file contents. This would only collide if its the same image or a hash collision which is a 1 in 2^160 chance. You can avoid having duplicate images this way however because you are creating a hash from the file it can be slower.
$filename = sha1_file($upload_file) . $ext;
Another option is tempnam It will create a temp file with a unique name.
Note: If PHP cannot create a file in the specified dir parameter, it falls back on the system default.
Basic example:
$filename = tempnam($dir, $prefix);
unlink($filename)//we don't need the tempfile just the name
Also note: If you change the filename it might not be unique.
You could use a timestamp in the date, that way you won't get the same filename/time twice.
Not certain exactly what your code looks like but you could do something like this:
$filename = uniqid() . $orig_filename;
Read this documentation on the PHP docs about uniqid for more information. It uses the datetime to output a unique identifier string.
You can use the uniqid()
function to generate a unique ID
/**
* Generate a unique ID
* @link http://www.php.net/manual/en/function.uniqid.php
* @param prefix string[optional] <p>
* Can be useful, for instance, if you generate identifiers
* simultaneously on several hosts that might happen to generate the
* identifier at the same microsecond.
* </p>
* <p>
* With an empty prefix, the returned string will
* be 13 characters long. If more_entropy is
* true, it will be 23 characters.
* </p>
* @param more_entropy bool[optional] <p>
* If set to true, uniqid will add additional
* entropy (using the combined linear congruential generator) at the end
* of the return value, which should make the results more unique.
* </p>
* @return string the unique identifier, as a string.
*/
function uniqid ($prefix = null, $more_entropy = null) {}