Auto Rename File Upload

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
typo
Forum Newbie
Posts: 4
Joined: Sun Apr 05, 2009 7:22 am

Auto Rename File Upload

Post by typo »

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.

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.";
        }
 
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.

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}";
}
 
Any help would be much appreciated.
nyoka
Forum Commoner
Posts: 45
Joined: Thu Apr 09, 2009 12:53 pm

Re: Auto Rename File Upload

Post by nyoka »

From what I can see the line:

Code: Select all

 
$now = date('Y-m-d-His');
 
Needs to be changed to call your function that generates the next number.

Hope this helps.
Post Reply