Question

I want to create a function which does rename the file and generate a unique name from its name, together with the user id. Below function is working properly but I'm not satisfied, kindly provide me the similar function.

if(is_array($file) and $file['name'] != '')
        {
            // getting unique file name
            $file['name'] = getUniqueFilename($file);

            $file_path = $file_root_path.$file['name'];
            if(move_uploaded_file($file['tmp_name'], $file_path)){$filename = $file['name'];}
            //
            if($oldfile != ''){delete_file($file_root_path.$oldfile);}
            return $filename;
        } // if ends
        else
        {
            return $oldfile;
        } // else ends

function getUniqueFilename($file)
    {
        if(is_array($file) and $file['name'] != '')
        {
            // getting file extension
            $fnarr          = explode(".", $file['name']);
            $file_extension = strtolower($fnarr[count($fnarr)-1]);

            // getting unique file name
            $file_name = substr(md5($file['name'].time()), 5, 15).".".$file_extension;
            return $file_name;
        } // ends for is_array check
        else
        {
            return '';
        } // else ends
    } // ends
Was it helpful?

Solution 2

Take a hash of the file contents, e.g. with sha1_file. That guarantees a unique name for each unique file. If the same file gets uploaded a second time, it will generate the same hash, so you're not even storing duplicates of identical files.

OTHER TIPS

Use php uniqid() to generate unique ids http://php.net/manual/en/function.uniqid.php

function getUniqueFilename($file)
{
    if(is_array($file) and $file['name'] != '')
    {
        // getting file extension
        $file_extension = pathinfo($file['name'], PATHINFO_EXTENSION);

        // getting unique file name
        $file_name = uniqid().".".$file_extension;

        while(file_exists('PATH_TO_WHERE_YOU_SAVE_FILE/'.$file_name)) {
            $file_name = uniqid().".".$file_extension;
        }

        return $file_name;
    } // ends for is_array check
    else
    {
        return '';
    } // else ends
} // ends

Please use this code, that may help you

<?php
  function tempdir($dir, $prefix='', $mode=0700)
  {
    if (substr($dir, -1) != '/') $dir .= '/';

    do
    {
      $path = $dir.$prefix.mt_rand(0, 9999999);
    } while (!mkdir($path, $mode));

    return $path;
  }
?>

Reference Link: http://www.php.net/manual/en/function.tempnam.php

You could create a filename with an [md5][1] hash salted with current [timestamp][2] and a random number.

Something like:

 function getUniqueFilename($file)
 {
   do {
     $name = md5(time().rand().$file['name']);
   } while (file_exists($path.$name);
   return $name;
 }

Being path the folder where you want your file created

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top