2012-04-28 54 views
1

我正嘗試在將圖像上傳到我的服務器時重命名圖像。這樣做通常有一個簡單的方法嗎?以下是我使用的PHP代碼。我想將它重命名爲一個變量,我將它作爲HTML表單的隱藏字段傳遞。PHP圖片上傳器重命名圖片?

//variable from hidden field on form which is from mysql database 
$imageName = $_POST['image_rename']; 

if ((($_FILES["file"]["type"] == "image/gif") || ($_FILES["file"]["type"] == "image/jpeg") || ($_FILES["file"]["type"] == "image/jpg") || ($_FILES["file"]["type"] == "image/pjpeg")) && ($_FILES["file"]["size"] < 8000000)) 
    { 
    if ($_FILES["file"]["error"] > 0) 
    { 
    echo "Return Code: " . $_FILES["file"]["error"] . "<br />"; 
    } 
    else 
    { 
    echo "Upload: " . $_FILES["file"]["name"] . "<br />"; 
    echo "Type: " . $_FILES["file"]["type"] . "<br />"; 
    echo "Size: " . ($_FILES["file"]["size"]/1024) . " Kb<br />"; 
    echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />"; 

    if (file_exists("../uploads/" . $_FILES["file"]["name"])) 
     { 
     echo $_FILES["file"]["name"] . " already exists. "; 
     } 
    else 
     { 
     move_uploaded_file($_FILES["file"]["tmp_name"], "../uploads/" . $_FILES["file"]["name"]); 
     echo "Stored in: " . "../uploads/" . $_FILES["file"]["name"]; 
     } 
    } 
    } 
else 
    { 
    echo "Invalid file"; 
    } 
+0

不要使用未經檢驗的輸入從客戶端,也可能是潛在的危險 – ilanco 2012-04-28 23:09:45

回答

1

嘗試改變move_uploaded_file()功能;在函數中添加你想要的名字。只要確保搶到合適的擴展,是這樣的:

$parts=explode('.',$_FILES['file']['name']); 
$newName=$imageName.'.'.$parts[(count($parts)-1)]; 
move_uploaded_file($_FILES['file']['tmp_name'],'../uploads/'.$newName); 
+1

你可以使用 end($ parts);而不是數 - 1 – Sedz 2012-04-29 00:29:54

0

變化

move_uploaded_file($_FILES["file"]["tmp_name"], "../uploads/" . $_FILES["file"]["name"]); 

move_uploaded_file($_FILES["file"]["tmp_name"], "../uploads/" . $imageName); 
+0

不使用擴展 – Sedz 2012-04-29 00:29:11

+0

沒有,因爲他說,他將提供文件名通過隱藏的輸入。 '$ imageName = $ _POST ['image_rename'];';) – fhugas 2012-04-29 01:21:00