2012-08-23 84 views
-1

請有人向我展示我需要更改代碼的位置,以便上傳的圖像被重命名爲「freddy」。如何使用此腳本重命名上傳圖像文件

但仍然帶有正確的現有擴展名,即JPG,PNG,GIF。

在此先感謝

<?php 
// define a constant for the maximum upload size 
define ('MAX_FILE_SIZE', 1024 * 50); 

if (array_key_exists('upload', $_POST)) { 
// define constant for upload folder 
define('UPLOAD_DIR', '/home/richard/public_html/testing/editable-images/'); 
// replace any spaces in original filename with underscores 


$file = str_replace(' ', '_', $_FILES['image']['name']); 
// create an array of permitted MIME types 
$permitted = array('image/gif', 'image/jpeg', 'image/pjpeg', 
'image/png'); 

// upload if file is OK 
if (in_array($_FILES['image']['type'], $permitted) 
    && $_FILES['image']['size'] > 0 
    && $_FILES['image']['size'] <= MAX_FILE_SIZE) { 
switch($_FILES['image']['error']) { 
    case 0: 
    // check if a file of the same name has been uploaded 
// Uncomment to stop overwritten files >>>>  if (!file_exists(UPLOAD_DIR . $file))  { 
     // move the file to the upload folder and rename it 
     $success = 
move_uploaded_file($_FILES['image']['tmp_name'], UPLOAD_DIR . 
$file); 
// Uncomment to stop overwritten files >>>> } else { 
// Uncomment to stop overwritten files >>>>  $result = 'A file of the same name    already exists.'; 
    // Uncomment to stop overwritten files >>>>>  } 
    if ($success) { 
     $result = "$file uploaded successfully."; 
    } else { 
     $result = "Error uploading $file. Please try again."; 
    } 
    break; 
    case 3: 
    case 6: 
    case 7: 
    case 8: 
    $result = "Error uploading $file. Please try again."; 
    break; 
    case 4: 
    $result = "You didn't select a file to be uploaded."; 
    } 
    } else { 
    $result = "$file is either too big or not an image."; 
    } 
    } 
?> 

回答

2
// get file extension 
$ext = end(explode($_FILES['image']['name'])); 

// name your file and preserve file extension 
$file = "freddy.".$ext; 

// create an array of permitted MIME types 
.... 
0

方法move_uploaded_file的檢查描述here

+0

這不是在所有 – Peter

+0

嗨,彼得,你的代碼已經幫我,但擴展並不顯示一個答案,該文件正在像freddy一樣上傳。沒有任何延伸。 任何想法,爲什麼這可能是? Thankyou – Lucy

+0

@Lucy change'list($ ext)'to'$ ext' – Peter