While uploading a file you may want to check if a file already exists in target directory then create a new file instead of replacing and rename new file with an incremental no.

Example

some_dir/some_file.png already exists, and you try to upload a file with name some_file.png again, so it should be uploaded as some_dir/some_file1.png or some_dir/some_file_cp1.png where _cp is the copy prefix.

You can use function below to get the renamed file name.

function rename_copy($targetFile, $copyPrefix = null) {

    $filename = basename($targetFile);

    $dir = pathinfo($targetFile, PATHINFO_DIRNAME);
    $name = pathinfo($targetFile, PATHINFO_FILENAME);
    $ext = pathinfo($targetFile, PATHINFO_EXTENSION);

    $index = 1;
    while(file_exists($dir . "/" . $filename)) {
        $filename = $name . $copyPrefix . ($index ++) . '.' . $ext;
    };

    return $dir . '/' . $filename;
}

If you want just incremental names without any prefix then use the function as

rename_copy("some_dir/some_file.png");

The above code will produce “some_dir/some_file1.png” if file already exists, otherwise it will return “some_dir/some_file.png”

If you need a copy prefix i.e _cp1, use it as below

rename_copy("some_dir/some_file.png", "_cp");

The above code will produce “some_dir/some_file_cp1.png” if file already exists, otherwise it will return “some_dir/some_file.png”

Advertisements