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;

Recommended Answers

All 15 Replies

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.





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;

    do {

        $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;        




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.


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

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

Member Avatar for diafol

Here's a way to do it...


    $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");

        mysql_query("INSERT INTO files SET filename = '$stored', version = $version");          
        $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">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>

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


This is based on a table...

CREATE TABLE `files` (
  `filename` VARCHAR(30) COLLATE utf8_unicode_ci DEFAULT NULL,
  `version` TINYINT(3) DEFAULT NULL,
  PRIMARY KEY (`file_id`)

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 :)


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


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.

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



wow, its kinda detailed, thanks lemme check :)


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


quick question what is the meaning or purpose of



Member Avatar for diafol

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


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!


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

if(!mysql_num_rows($r)) /* IF NEW FILENAME, INSERT */


Member Avatar for diafol

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.