如果在php yii中有重复值,则在文件末尾添加一个值 [英] Adding a value to the end of a file if it's duplicate in php yii
问题描述
我正在尝试处理重复的文件名.如果一个用户上载一个名为"file"的文件,那么另一个用户上载一个名为"file"的文件,我希望能够在新文件中添加一个1,因此现在称为"1file".我能够做到这一点,但是我的问题是,当某人第三次上载文件"时,它覆盖了"1file",我需要增加1.我正在使用yii框架
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,
));
}
推荐答案
好吧,我认为您有两种选择:
Well I think you have two options:
-
在文件名的末尾添加类似
microtime()
的内容,这样就几乎不可能两次拥有相同的文件名.
append something like
microtime()
to the end of the filename, that way it's virtually impossible for you to have the same file name twice.
如果您需要按顺序保存文件,并且不想使用上述方法,则必须将最后插入的号码存储在数据库中,然后检索它,增加并再次存储.
if you need the files to be kept in order and don't want to use the approach above, then you'd have to store the last inserted number in a database and then retrieve it, increment and store again.
我也使用YII框架,但是不记得任何与Yii有关的东西都可以在这里为您提供帮助.
I use the YII framework as well, but can't remember of anything specific to Yii that would help you here.
这篇关于如果在php yii中有重复值,则在文件末尾添加一个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!