PHP - md5和唯一的$ _file名称

时间:2013-10-20 10:19:23

标签: php

我有一个用于将图像上传到服务器的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 个答案:

答案 0 :(得分:2)

按如下方式更改$uploadfile声明:

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

答案 1 :(得分: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'])));

答案 2 :(得分:1)

只需替换basename上的md5

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

答案 3 :(得分:0)

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

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

并在脚本中使用$targetFile代替$_FILES['user_image']['name']

//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) ;

}