PHP: Generate a unique filename for a given directory

This function will generate a filename unique to specified directory. If you’re using it to create filenames for uploaded images, for example, you can give it a path to your upload folder an extension such as ‘jpg’.

It will generate the filename using the characters specified in the function, you can modify it as desired. I chose to omit uppercase letters in case you are running this on a Windows system (case insensitive).

 * Converts large hexidecimal numbers into decimal strings.
 * @param string $hex Hexidecimal number
 * @return string Decimal number
 * @see

function bchexdec($hex)
    $dec = 0;
    $len = strlen($hex);
    for ($i = 1; $i <= $len; $i++) {
        $dec = bcadd($dec, bcmul(strval(hexdec($hex[$i - 1])), bcpow('16', strval($len - $i))));
    return $dec;

function base_encode($val, $base=62, $chars='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ') {
    if(!$base) $base = strlen($chars);
    $str = '';
    do {
        $m = bcmod($val, $base);
        $str = $chars[$m] . $str;
        $val = bcdiv(bcsub($val, $m), $base);
    } while(bccomp($val,0)>0);
    return $str;

function unique_filename($dir, $ext='') {
    do {
        $filename = $dir.'/'.base_encode(bchexdec(uniqid()), null, '0123456789abcdefghijklmnopqrstuvwxyz_-');
        if($ext) $filename .= '.'.$ext;
    return $filename;
Posted in

Leave a comment

Leave a Reply

Your email address will not be published. Required fields are marked *