2012-08-23 57 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