Controlla se il file esiste / Aggiungi numero al nome - Trucchi CSS

Anonim

Se il nome del file esiste, restituisce il nuovo nome del file con _number aggiunto in modo da non sovrascriverlo.

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; )

L'esempio restituisce:

myfile.jpg.webp
myfile_0.jpg.webp
myfile_1.jpg.webp