如何在上传时自动重命名图像文件名?

How to rename automatically image file names while uploading?

这是我的上传功能代码:

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;
}

此功能不能自动重命名文件名,如果两个文件名相同,它会将新图像文件替换为现有文件。

如何更改上述功能以在上传到服务器时自动重命名文件?

非常感谢

获取扩展名:

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

然后更改此行:

$destinationName = $file['name'];

到附加到时间戳的文件的 sha1 哈希的组合,扩展名为:

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

使用这样的东西:

$destionationFile = $destinationDir . '/' . $destinationName; 
if(is_file($destinationFile))
{
$destinationName = basename($destinationName).'_'.hash('sha256', time().rand(9999, 999999)).'.'.pathinfo($destinationName)['extension'];
$destionationFile = $destinationDir . '/' . $destinationName;
}