计数器在文件名中

时间:2015-12-10 20:02:57

标签: php loops laravel filenames laravel-5.1

所以问题是:每当用户上传文件时,都会检查该文件是否存在于目录中。如果存在,则在文件名中应将_n作为后缀,其中n是数字。所以在第二次上传时,文件名看起来应该像file_2.extension这应该用某种循环来完成吗?

if ($request->hasFile('file')) {
        $file = $request->file('file');
        $user = Auth::id();
        $filename = $file->getClientOriginalName();
        $extension = $file->getClientOriginalExtension();
        $onlyname = basename($filename, $extension);
        $filePath = 'uploads\\'.$user.'\\'.$file->getClientOriginalName();
        if (file_exists($filePath)) {
            if($file->move('uploads\\'.$user, $onlyname.'_'.$counter.'.'.$extension)){                
                $uploadHandler = new UploadHandler();       
                $uploadAttributes = $uploadHandler->uploadAttributes($request);   
            }
        }                     
    }

2 个答案:

答案 0 :(得分:2)

是的,您需要while循环

if ($request->hasFile('file')) {
    $file = $request->file('file');
    $user = Auth::id();
    $filename = $file->getClientOriginalName();
    $extension = $file->getClientOriginalExtension();
    $onlyname = basename($filename, $extension);
    $filePath = 'uploads\\'.$user.'\\'.$file->getClientOriginalName();

    if (file_exists($filePath)) {
        $counter = 2;
        while (file_exists($filePath)){
            $filePath = 'uploads\\'.$user. $onlyname.'_'.$counter.'.'.$extension;
            $counter ++;
        }
    }
    if($file->move($filePath)){                
        $uploadHandler = new UploadHandler();       
        $uploadAttributes = $uploadHandler->uploadAttributes($request);   
    }                     
}

答案 1 :(得分:1)

是的,您可以使用while循环,如下所示:

while( file_exists($filePath) ) {
     // increment your $counter and update $filePath accordingly
}