Search code examples
phpfopenfile-exists

Add number to fopen link if that file name already exists


Basically, I want to continue adding numbers each time the file already existed. So if $url.php exists, make it $url-1.php. If $url-1.php exists, then make it $url-2.php, and so forth.

This is what I already came up with, but I think it'll only work the first time.

if(file_exists($url.php)) {
    $fh = fopen("$url-1.php", "a");
    fwrite($fh, $text);
} else {
    $fh = fopen("$url.php", "a");
    fwrite($fh, $text);
}
fclose($fh);

Solution

  • I use while loops for scenarios like this.

    $filename=$url;//Presuming '$url' doesn't have php extension already
    $fn=$filename.'.php';
    $i=1;
    while(file_exists($fn)){
       $fn=$filename.'-'.$i.'.php';
       $i++;
    }
    $fh=fopen($fn,'a');
    fwrite($fh,$text);
    fclose($fh);
    

    All that said, this direction of solutions does not scale well. You do not want to be checking over a 100 file_exists routinely.