I am trying to handle duplicate filenames. if a user uploads a file name called "file" then another user uploads a file called "file" I want to be able to add a 1 to the new file so it would be now called "1file". I am able to do this but my issue is when someone uploades "file" for a third time it overrides "1file" I need the 1 to increase. I am using The yii framework
Here is my function in my controller:
function actionIndex(){
//$dir = Yii::getPathOfAlias('application.images');
//$dir is a variable that will hold the files uploaded
$dir = Yii::app()->controller->module->cssFolder;
//uploaded is a flag to see if we need to display a success/error message
$uploaded = false;
$model=new CssUpload();
if(isset($_POST['CssUpload'])){
$model->attributes=$_POST['CssUpload'];
//see if file is correct format and allows us to see and save the file
$file=CUploadedFile::getInstance($model,'file');
if($model->validate()){
$i = 0;
//trying to add a int to the front/end of a duplicate file
//able to handle the duplicate one time then gets stuck in an infinete loop
//(it actually breaks on the first duplictae but it uploads)
do{
if(file_exists($dir.'/'.$file)){
//increase $i by 1 every time it loops through
$i++;
//for test purposes only
echo $i;
//upload the file
$uploaded = $file->saveAs($dir.'/'.$i.$file->getName());
//stops the infinute loop
break;
}
}while(file_exists($dir.'/'.$file));
//upload the original file with no new extensions
$uploaded = $file->saveAs($dir.'/'.$file->getName());
}
}
$this->render('index', array(
'model' => $model,
'uploaded' => $uploaded,
'dir' => $dir,
));
}