如何使用此脚本在上载时重命名图像文件

时间:2012-08-23 10:39:22

标签: php image upload

请有人告诉我需要更改代码的位置,以便上传的图片重命名为“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 个答案:

答案 0 :(得分: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
....

答案 1 :(得分:0)

检查方法move_uploaded_file here

的描述