0

我有一个用于将图像上传到服务器的 PHP 函数,

但我很困惑,我想给当前上传的文件一个唯一的 md5 名称。这是我的代码:

if ((getimagesize($_FILES['user_image']['tmp_name']) >0) && $_FILES['user_image']['size'] > 0 && ($_FILES['user_image']['size'] < 1048576)){

        $uploaddir  = DIR.'/images/';
        $uploadfile = $uploaddir . basename($_FILES['user_image']['name']);
        move_uploaded_file($_FILES['user_image']['tmp_name'], $uploadfile);

        // check if user have already uploaded an image, then delete 
        //it before uploading new one

        $old_file = db_user_image($user, 'image');
        if (strlen($old_file)){ 
            $delete = $uploaddir.$old_file;
            if (file_exists($delete))  
                unlink ($delete); 
        }

        db_save_user_image($user, 'image', $_FILES['user_image']['name']) ;

}   

请告诉我如何为这些文件提供唯一的 md5 名称。

4

4 回答 4

2

更改您的$uploadfile声明如下:

$ext = pathinfo( $_FILES['user_image']['name'], PATHINFO_EXTENSION);
$uploadfile = $uploaddir . md5(basename($_FILES['user_image']['name']) ).$ext;
于 2013-10-20T10:23:53.507 回答
1

如果您只想为文件提供 md5 名称,则需要更改行

$uploadfile = $uploaddir . basename($_FILES['user_image']['name']);

$uploadfile = $uploaddir . md5(basename($_FILES['user_image']['name']));

db_save_user_image($user, 'image', $_FILES['user_image']['name']) ;

db_save_user_image($user, 'image', md5(basename($_FILES['user_image']['name'])));
于 2013-10-20T10:23:42.883 回答
1

只需更换basename.md5

basename返回路径的尾随名称组件

于 2013-10-20T10:23:53.333 回答
0

我添加了时间戳并使用md5(). 它应该为文件生成一个唯一的名称。

   $targetFile = md5(time()).$_FILES['user_image']['name'];

并用于$targetFile代替$_FILES['user_image']['name']in 脚本。

//Code
if ((getimagesize($_FILES['user_image']['tmp_name']) >0) && $_FILES['user_image']['size'] > 0 && ($_FILES['user_image']['size'] < 1048576)){

    $uploaddir  = DIR.'/images/';
    $targetFile = md5(time()).$_FILES['user_image']['name'];
    $uploadfile = $uploaddir.$targetFile;
    move_uploaded_file($_FILES['user_image']['tmp_name'], $uploadfile);

    // check if user have already uploaded an image, then delete 
    //it before uploading new one

    $old_file = db_user_image($user, 'image');
    if (strlen($old_file)){ 
        $delete = $uploaddir.$old_file;
        if (file_exists($delete))  
            unlink ($delete); 
    }

    db_save_user_image($user, 'image', $targetFile) ;

}

于 2013-10-20T10:30:56.920 回答