Auto Rename File Upload
Posted: Sun Apr 05, 2009 8:31 am
I currently have an upload script which handles multiple file uploads. After the usual sanitation checks it moves onto a conditional statement to check whether the name of the file being uploaded already exists in the upload location. If it does it currently renames it by pre-pending a timestamp to the file name.
What I'd like to do is to make it more readable and simply append a '01' or '02' etc, to the filename. How can I replace the timestamp rename to the number rename? I have a function which performs this action (looping through the directory contents, checking for the matching filename with the highest number and then append the next number in the series) but I'm not sure how to link this in with the upload script I have.
Any help would be much appreciated.
Code: Select all
if ($sizeOK && $typeOK) {
switch($_FILES['image']['error'][$number]) {
case 0:
// check if a file of the same name has been uploaded
if (!file_exists(UPLOAD_DIR.$file)) {
// move the file to the upload folder and rename it
$success = move_uploaded_file($_FILES['image']['tmp_name'][$number], UPLOAD_DIR.$file);
}
else {
// getNextFilename include to go here?
// get the date and time
ini_set('date.timezone', 'Europe/London');
$now = date('Y-m-d-His');
$success = move_uploaded_file($_FILES['image']['tmp_name'][$number], UPLOAD_DIR.$now.$file);
}
if ($success) {
$result[] = "$file uploaded successfully";
}
else {
$result[] = "Error uploading $file. Please try again.";
}
break;
case 3:
$result[] = "Error uploading $file. Please try again.";
default:
$result[] = "System error uploading $file. Contact webmaster.";
}
}
elseif ($_FILES['image']['error'][$number] == 4) {
$result[] = 'No file selected';
}
else {
$result[] = "$file cannot be uploaded. Maximum size: $max. Acceptable file types: gif, jpg, png.";
}
Code: Select all
function getNextFilename($dir, $prefix, $type) {
// run some security checks on the arguments supplied
if (!is_dir($dir)) return false;
if (!preg_match('/^[-._a-z0-9]+$/i', $prefix)) return false;
$permittedTypes = array('txt', 'doc', 'pdf', 'jpg', 'jpeg', 'gif', 'png');
if (!in_array(strtolower($type), $permittedTypes)) return false;
// if the checks are OK, get an array of the directory contents
$existing = scandir($dir);
// create a search pattern for filenames that match the prefix and type
$pattern = '/^'.$prefix.'(\d+)\.'.$type.'$/i';
$nums = array();
// loop through the directory
// get the numbers from all files that match the pattern
foreach ($existing as $file) {
if (preg_match($pattern, $file, $m)) {
$nums[] = intval($m[1]);
}
}
// find the highest number and increase it by 1
// if no file yet created, assign it number 1
$next = $nums ? max($nums)+1 : 1;
// calculate how many zeros to prefix the number with
if ($next < 10) {
$zeros = '00';
}
elseif ($next < 100) {
$zeros = '0';
}
else {
$zeros = '' ;
}
// return the next filename in the series
return "{$prefix}{$zeros}{$next}.{$type}";
}