hikaru12 Posted June 21, 2015 Share Posted June 21, 2015 If I upload a file with the same name as another one the most recent one overrides the file uploaded. As a result, I've begun adding timestamps to all files uploaded with the following code: $targetPath = dirname( __FILE__ ) . DIRECTORY_SEPARATOR . $upload_dir . DIRECTORY_SEPARATOR; $mainFile = $targetPath.date("Y-m-d H-i-s").'-'. $_FILES['file']['name']; So files currently look like: 06-20-15 07:08:00PM-somefile.php I'd like to change from that format to a more human readable format. Ideally, I'd like to use the a counter for version control. What I'd like to do is have a form with a selectbox that says the following: File Upload: Major or Minor Version selectbox If the user selects Major version I want a counter to increment by "1" and apply "Version 1 -", "Version-2", etc. and append that to the filename before the filename and extension by performing the following checks: If the file name already exists then check: If the file size is different or If the date/time modified is different If the user selects Minor version from the above form then I want a counter to increment by "0.1" and apply "Version 0.1 -", "Version 0.2 -", etc. In this way by selecting the same file name I can have a combination of Version numbers which will give me an idea of what sort of changes have occurred to the file. For example, by submitting the file test.php twice, one as a major version, and another time as a minor version I should end up with a file that is now renamed "Version 1.1 - test.php" Please ask if you need clarification. Thanks so much for the help. Quote Link to comment https://forums.phpfreaks.com/topic/296938-renaming-file-on-upload/ Share on other sites More sharing options...
hikaru12 Posted June 21, 2015 Author Share Posted June 21, 2015 Sorry for this double post but I have the following code which accomplishes what I need except for the minor revision. The code just times out so I'm thinking it has something to do with how my variables are assigned. if ( isset( $_POST['addfile'] ) ) { // variables define('UPLOAD_DIR', 'repository/'); $fileName = $_FILES['fileToUpload']; if($_POST['rev_type'] == 'Minor') { function update_file_name_minor($file) { $pos = strrpos($file,'.'); $ext = substr($file,$pos); $dir = strrpos($file,'/'); $dr = substr($file,0,($dir+1)); $arr = explode('/',$file); $fName = substr($arr[(count($arr) - 1)], 0, -strlen($ext)); $exist = FALSE; $i = 0.01; while(!$exist) { $file = $dr.$fName.'_'.'Ver '.$i.$ext; if(!file_exists($file)) $exist = TRUE; $i2 = $i + 0.01; } return $file; } // check for which action should be taken if file already exist if(file_exists(UPLOAD_DIR . $fileName['name'])) { $updatedFileName = update_file_name_minor(UPLOAD_DIR.$fileName['name']); move_uploaded_file($fileName['tmp_name'], $updatedFileName); echo "You have successfully uploaded and renamed the file as a minor revision."; } else { move_uploaded_file($fileName['tmp_name'], UPLOAD_DIR.$fileName['name']); echo "You have successfully uploaded the file."; } } elseif($_POST['rev_type'] == 'Major') { function update_file_name_major($file) { $pos = strrpos($file,'.'); $ext = substr($file,$pos); $dir = strrpos($file,'/'); $dr = substr($file,0,($dir+1)); $arr = explode('/',$file); $fName = substr($arr[(count($arr) - 1)], 0, -strlen($ext)); $exist = FALSE; $i = 2; while(!$exist) { $file = $dr.$fName.'_'.'Ver '.$i.$ext; if(!file_exists($file)) $exist = TRUE; $i++; } return $file; } // check for which action should be taken if file already exist if(file_exists(UPLOAD_DIR . $fileName['name'])) { $updatedFileName = update_file_name_major(UPLOAD_DIR.$fileName['name']); move_uploaded_file($fileName['tmp_name'], $updatedFileName); echo "You have successfully uploaded and renamed the file as a major revision."; } else { move_uploaded_file($fileName['tmp_name'], UPLOAD_DIR.$fileName['name']); echo "You have successfully uploaded the file."; } } } //main if Quote Link to comment https://forums.phpfreaks.com/topic/296938-renaming-file-on-upload/#findComment-1514492 Share on other sites More sharing options...
Ch0cu3r Posted June 21, 2015 Share Posted June 21, 2015 Try define('UPLOAD_DIR', 'repository/'); // default major, minor values; $minor = 1; $major = 0; if (isset( $_POST['addfile'])) { // get the filename and extension of the uploaded file $path = pathinfo($_FILES['fileToUpload']['name']); $filename = $path['filename']; $extension = $path['extension']; // find existing uploaded versions $existingFileVersions = glob(UPLOAD_DIR . "$filename *.*.$extension"); if($existingFileVersions) { // get the last file $lastFileVersion = end($existingFileVersions); // extract the major and minor version from the filename preg_match('/(.*) (\d+).(\d+)$/', pathinfo($lastFileVersion, PATHINFO_FILENAME), $m); list(, $filename, $major, $minor) = $m; // increment the major/minor versions switch($_POST['rev_type']) { case 'major': $major += 1; break; case 'minor': $minor += 1; $minor = sprintf('%02d', $minor); // format minor version to two digits 01, 02 .. 10 etc break; } } // set the new filename $updatedFilename = UPLOAD_DIR . "$filename $major.$minor.$extension"; // upload file if(move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $updatedFilename)) { echo "You have successfully uploaded and renamed the file as a '{$_POST['rev_type']}' revision."; echo "<p>FILE: $updatedFilename</p>"; } } Quote Link to comment https://forums.phpfreaks.com/topic/296938-renaming-file-on-upload/#findComment-1514508 Share on other sites More sharing options...
hikaru12 Posted June 23, 2015 Author Share Posted June 23, 2015 I tried your code but whenever I try to go from two minor versions say 0.1 to 0.2 it replaces 0.1. I may not have been clear as to what I wanted because Major to Minor works great it produces the desired output of 1.01 but not 1.02. Anyway, I put something together myself. I'm having two issues, however. 1) The below script works with filenames and renames them correctly. So two minor versions will be 0.1, 0.2, etc. However, when they're put inside the database the name is always recorded as 0.1 no matter how many times I upload a minor file. 2) I'm having an issue in the database where I stored the filename of major versions but it keeps the first character of the name. For example, if I had a filed named test_Ver 1.php, the database would record it as ttest_Ver 1.php. It doesn't seem to have that issue when I record the name of minor versioned files however. Do you mind taking a look? Thanks in advance. <?php function update_file_name_major($file) { $pos = strrpos($file,'.'); $ext = substr($file,$pos); $dir = strrpos($file,'/'); $dr = substr($file,0,($dir+1)); $arr = explode('/',$file); $fName = substr($arr[(count($arr) - 1)], 0, -strlen($ext)); $exist = FALSE; $i = 1; while(!$exist) { $file = $dr.$fName.'_'.'Ver '.$i.$ext; if(!file_exists($file)) $exist = TRUE; $i++; } return $file; } function get_file_name_major_latest($file) { $pos = strrpos($file,'.'); $ext = substr($file,$pos); $dir = strrpos($file,'/'); $dr = substr($file,0,($dir+1)); $arr = explode('/',$file); $fName = substr($arr[(count($arr) - 1)], 0, -strlen($ext)); $exist = FALSE; $i = 1; while(!$exist) { $file = $dr.$fName.'_'.'Ver '.$i.$ext; if(!file_exists($file)){ $exist = TRUE; return $i; } $i++; } return 0; } function update_file_name_minor($file, $latest_major = 0) { $pos = strrpos($file,'.'); $ext = substr($file,$pos); $dir = strrpos($file,'/'); $dr = str_replace(end(explode("/",$file)), '', $file); $arr = explode('/',$file); $fName = current(explode(".",end(explode("/",$file)))); $exist = FALSE; $i = (float) $latest_major. '.01'; while(!$exist) { $file = $dr.$fName.'_'.'Ver '.$i.$ext; if(!file_exists($file)) $exist = TRUE; $i += 0.01; } return $file; } if ( isset( $_POST['addfile'] ) ) { // variables define('UPLOAD_DIR', 'repository/'); $fileName = $_FILES['file']; $file_type = $_FILES['file']['type']; $projectname=$_POST['projectname']; $comments=$_POST['comments']; if($_POST['rev_type'] == 'Minor') { // check for which action should be taken if file already exist if(file_exists(UPLOAD_DIR . $fileName['name'])) { $latest_major = 0; if(update_file_name_major(UPLOAD_DIR.$fileName['name']) != UPLOAD_DIR.$fileName['name']){ $latest_major = get_file_name_major_latest(UPLOAD_DIR.$fileName['name']); --$latest_major; } $updatedFileName = update_file_name_minor(UPLOAD_DIR.$fileName['name'], $latest_major); move_uploaded_file($fileName['tmp_name'], $updatedFileName); include 'db.php'; $updatedFileName2 = update_file_name_minor($fileName['name'], $latest_major); preg_match('/([0-9.+])/', "$updatedFileName2", $matches); $clean = $matches[1]; $add = mysql_query("INSERT INTO `myversions`(filename, filetype, vernum, projectname, comments, created) VALUES ('$updatedFileName2', '$file_type','$clean','$projectname','$comments', NOW())"); echo "You have successfully uploaded and renamed the file as a minor revision."; } else { move_uploaded_file($fileName['tmp_name'], UPLOAD_DIR.$fileName['name']); include 'db.php'; $baseFile = $fileName['name']; $add = mysql_query("INSERT INTO `myversions`(filename, filetype, projectname, comments, created) VALUES ('$baseFile','$file_type','$projectname','$comments', NOW())"); echo "You have successfully uploaded the file."; } } elseif($_POST['rev_type'] == 'Major') { // check for which action should be taken if file already exist if(file_exists(UPLOAD_DIR . $fileName['name'])) { $updatedFileName = update_file_name_major(UPLOAD_DIR.$fileName['name']); move_uploaded_file($fileName['tmp_name'], $updatedFileName); include 'db.php'; $updatedFileName2 = update_file_name_major( $fileName['name']); preg_match('/([0-9.+])/', "$updatedFileName2", $matches); $clean = $matches[0]; $add = mysql_query("INSERT INTO `myversions`(filename, filetype, vernum, projectname, comments, created) VALUES ('$updatedFileName2', '$file_type','$clean','$projectname','$comments', NOW())"); echo "You have successfully uploaded and renamed the file as a major revision."; } else { move_uploaded_file($fileName['tmp_name'], UPLOAD_DIR.$fileName['name']); include 'db.php'; $baseFile = $fileName['name']; $add = mysql_query("INSERT INTO `myversions`(filename, filetype, projectname, comments, created) VALUES ('$baseFile','$file_type','$projectname','$comments', NOW())"); echo "You have successfully uploaded the file."; } } } //main if ?> Quote Link to comment https://forums.phpfreaks.com/topic/296938-renaming-file-on-upload/#findComment-1514654 Share on other sites More sharing options...
Solution hikaru12 Posted June 23, 2015 Author Solution Share Posted June 23, 2015 Solved it. Used the following to get the last added file and got the name directly from the horses mouth. Couldn't be easier to work with than that. $path = "repository/"; $latest_ctime = 0; $latest_filename = ''; $d = dir($path); while (false !== ($entry = $d->read())) { $filepath = "{$path}/{$entry}"; // could do also other checks than just checking whether the entry is a file if (is_file($filepath) && filectime($filepath) > $latest_ctime) { $latest_ctime = filectime($filepath); $latest_filename = $entry; } } Quote Link to comment https://forums.phpfreaks.com/topic/296938-renaming-file-on-upload/#findComment-1514656 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.