2013-10-20 68 views
0

我有一個形象uploding到服務器的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名稱。

+1

...和?你對什麼感到困惑?你卡在哪裏? –

+0

如何爲此文件提供唯一的md5名稱? – user007

+0

這對我來說沒有任何意義。 md5總和並不比原始文件名更獨特,換句話說,具有相同名稱的兩個文件將導致相同的md5散列。 – hek2mgl

回答

2
的名字組件,如下

更改$uploadfile聲明:

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

嗨。阿邁勒。那個md5/uniqid不會破壞擴展嗎? –

+0

@ShankarDamodaran:看到更新後的答案:) –

+0

很酷!+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']))); 
+1

和唯一的名字?所以它不會覆蓋任何文件 – user007

+1

md5是非常獨特的,你必須生成許多MD5哈希來獲得名稱衝突。 –

+0

好的,謝謝澄清 – user007

1

只需在md5上替換basename即可。

basename回報尾隨路徑

0

我已經加入時間戳和使用md5()加密它。它應該爲文件生成一個唯一的名稱。

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

和到位的$_FILES['user_image']['name']在腳本中使用$targetFile

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

}

+0

md5是一個散列函數,你不用「加密」任何東西。 – 1615903