hi guys,

am testing this script, but its not working.

my requirements:
current file in database and in folder is 135.docx, and if i want to update it by uploading a new file, the new filename should be 135_1.docx , if update again it must be 135_2.docx and so on, the word file will just keep adding up in the folder but the database will just update its row data.

$infile = 135.docx
if ($pos = strrpos($infile, '.')) { 
    $name = substr($infile, 0, $pos); 
    $ext = substr($infile, $pos); 
} else { 
    $name = $infile; 
}

    $testname = $name.$ext; 

    //$newpath = $target.'/'.$infile;
    $newpath = $target.$infile;
    $name_inc = $infile;

    $counter = 1;
    while (file_exists($newpath)) {
       $name_inc = $name.'_'.$counter.".".$ext;

       $newpath = $target.'/'.$name_inc;
       $counter++;
    }
Member Avatar for diafol

When you say the file keeps adding up in the folder, do you want to keep the original files too?

If not, maybe it's easier to keep the same filename (overwrite), but just increment the DB table 'version' field.

e.g.

files

file_id
filename
location
version

Hai;

Use the following codes for rename the file name, if any file with same name exist on upload path.

$tempFile = $_FILES['txtFile']['tmp_name'];
    $targetPath = 'uploadfolder/';
    $newFileName =$_FILES['txtFile']['name'];
    $targetFile =  str_replace('//','/', $targetPath) . $newFileName;

    $cpy=0;
    do {

        if($cpy>0)
        $fileName="copy_".$cpy.str_replace(' ','_', ((isset($_FILES['file']['tmp_name']) && is_uploaded_file($_FILES['file']['tmp_name']))? $_FILES['file']['name'] : $_FILES['Filedata']['name']));
        else $fileName=str_replace(' ','_', ((isset($_FILES['file']['tmp_name']) && is_uploaded_file($_FILES['file']['tmp_name']))? $_FILES['file']['name'] : $_FILES['Filedata']['name']));
        $targetFile =  str_replace('//','/',$targetPath) .$fileName;        

        $cpy++;
    }while(is_file($targetFile));

    move_uploaded_file($tempFile,$targetFile);

@diafol

yes i want to keep the original files in the folder, your suggestion is also good, having version field in DB table. i will think about this.

Member Avatar for diafol

OK, in which case, you need to do something like Bachov suggests. Keeping original files means that you need to provide a new unique filename. Instead of just incrementing and looping you could use a datestamp or timestamp...

$file = $filename . '_' . time() . $file_extension;

Just an alternative maybe.

@bachov

thanks for the script, i have some clarification:
what are these?

$FILES['txtFile']['name'];
$_FILES['file']['tmp_name']; (file to upload?)
$_FILES['Filedata']['name';
"copy
" (is this the file in my DB?)

Member Avatar for diafol

Here's a way to do it...

<?php

if($_FILES)
{
    $link = mysql_connect('localhost', 'root', '');
    if (!$link) {
        die('Not connected : ' . mysql_error());
    }

    $db_selected = mysql_select_db('daniweb', $link);
    if (!$db_selected) {
        die ('Can\'t use daniweb : ' . mysql_error());
    }

    $stored = mysql_real_escape_string($_FILES['file']['name']);
    $version = 1;
    $pi = pathinfo($_FILES['file']['name']);
    $filename = $pi['filename'];
    $extension = '.' . $pi['extension']; 

    $r = mysql_query("SELECT version FROM files WHERE filename = '$stored' LIMIT 1");

    if(!mysql_num_rows($r)){
        mysql_query("INSERT INTO files SET filename = '$stored', version = $version");          
    }else{
        $d = mysql_fetch_assoc($r);
        $version = $d['version'] + 1;
        mysql_query("UPDATE files SET version = $version WHERE filename = '$stored'");
    }

    $newfile = $filename . '_' . $version . $extension;
    move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $newfile);
    echo "Saved as $newfile";   
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<style>
</style>
</head>

<body>
<form method="post" enctype="multipart/form-data">
<input type="file" name="file" id="file" />
<input type="submit" value="Show" name="sub" />
</form>

</body>
</html>

This is based on a table...

CREATE TABLE `files` (
  `file_id` INT(5) UNSIGNED NOT NULL AUTO_INCREMENT,
  `filename` VARCHAR(30) COLLATE utf8_unicode_ci DEFAULT NULL,
  `version` TINYINT(3) DEFAULT NULL,
  PRIMARY KEY (`file_id`)
) ENGINE=INNODB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci

Note - there is absolutely no error checking on queries and file upload. I'm using mysql_* functions for clarity - use PDO or mysqli.

This assumes that user(s) will be uploading files with duplicate names, not adding their own version numbers.

This solution avoids having to loop through a directory for files with a certain prefix in the name.

I like it, even if I do say so myself :)

//EDIT

You may have noticed that you could do away with the incrementing version from record and just do...

"UPDATE files SET version = version + 1 WHERE filename = '$stored'"
commented: perfect +2

@diafol

thats also good alternative, however, im having difficulty make the increment to work. i guess if i make it work, i can increment any value/function. im keeping in mind you suggestions after i work this out :)

so far am analyzing and testing @bachov script

and for the moment, i will just increment the eq(File ID 135.docx) to 135_1.docx in same row ID 135 while i will keep the old files in folder.

sample:
ID - filename - (folder)
135 - 135.docx - 135.docx
135 - 135_1.docx - 135_1.docx
135 - 135_2.docx - 135_2.docx

thanks

@diafol

wow, its kinda detailed, thanks lemme check :)

@diafol

your script works perfectly, am very thankful, i guess i can mark this as solved. cheers!

@diafol

quick question what is the meaning or purpose of

if($_FILES)

thanks

Member Avatar for diafol

just to see if a file has beenloaded in the file input control

@diafol

ok great, because before i was using this one

$vbasename = basename($_FILES['upfile']['name']);
if (!empty($vbasename))

just to know if there is a file to upload.

thanks a lot! cheers!

@diafol

hi, before i mark solved this thread, just a question:
does this line means

if(!mysql_num_rows($r)) /* IF NEW FILENAME, INSERT */
ELSE /* IF SAME FILE NAME, UPDATE */

thanks.

Member Avatar for diafol
if(!mysql_num_rows($r)) 

Means if a record doen't exist (i.e. that particular filename has not been uploaded before - so do an insert otherwise update the database by incrementing the version number)

all is clear. thanks a lot! cheers!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.