Search code examples
phpfile-uploadimage-uploadingfile-rename

How to rename automatically image file names while uploading?


Here's my upload function code:

function upload(&$file, $destinationDir = "", $destinationName = "", $secure = true){
    $ret = false;
    if (isset($file['tmp_name']) && isset($file['name'])){
        if ($destinationName == ''){
            $destinationName = $file['name'];
        }

        $destinationFile = $destinationDir . '/' . $destinationName;
        if (move_uploaded_file($file['tmp_name'], $destinationFile)){
            if ($secure){
                chmod($destinationFile, 0644);
            }

            $ret = true;
        }
    }

    return $ret;
}

This function can't rename file names automatically, if two files name are same, it will replace new image file to existing file.

How can I change this above function to rename files automatically while uploading to server?

Thank you very much


Solution

  • Get the extension:

    //Get extension
    $ext = pathinfo($file["name"], PATHINFO_EXTENSION);
    

    Then change this line:

    $destinationName = $file['name'];
    

    to a combination of the sha1 hash of the file appended to the timestamp, with the extension:

    $destinationName = sha1_file($file["tmp_name"]).time().".".$ext;