Tutorial Check if File Exists / Append Number to Name

by in , 0

If the file name exists, returns new file name with _number appended so you don't overwrite it.

function file_newname($path, $filename){
    if ($pos = strrpos($filename, '.')) {
           $name = substr($filename, 0, $pos);
           $ext = substr($filename, $pos);
    } else {
           $name = $filename;
    }

    $newpath = $path.'/'.$filename;
    $newname = $filename;
    $counter = 0;
    while (file_exists($newpath)) {
           $newname = $name .'_'. $counter . $ext;
           $newpath = $path.'/'.$newname;
           $counter++;
     }

    return $newname;
}

Example returns:

myfile.jpg
myfile_0.jpg
myfile_1.jpg

Leave a Reply