如果该文件名已经存在,则在fopen链接中添加数字


Add number to fopen link if that file name already exists

基本上,我想在每次文件已经存在时继续添加数字。如果$url.php存在,就写成$url-1.php。如果存在$url-1.php,则使其为$url-2.php,以此类推。

这是我已经想到的,但我想它只会第一次奏效。

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

我在这种情况下使用while循环。

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

尽管如此,这个解决方案的方向不能很好地扩展。您不希望例行检查100个file_exists

使用带有计数器变量$i的while循环。继续增加计数器,直到file_exists()返回false。此时,while循环退出,使用$i的当前值对文件名调用fopen();

if(file_exists("$url.php")) {
  $fh = fopen("$url-1.php", "a");
  fwrite($fh, $text);
} else {
  $i = 1;
  // Loop while checking file_exists() with the current value of $i
  while (file_exists("$url-$i.php")) {
    $i++;
  }
  // Now you have a value for `$i` which doesn't yet exist
  $fh = fopen("$url-$i.php", "a");
  fwrite($fh, $text);
}
fclose($fh);

我正在寻找类似这样的东西,并根据我的需求扩展了Shad的答案。我需要确保文件上传不会覆盖服务器上已经存在的文件。我知道它还没有"保存",因为它不能处理没有扩展名的文件。但也许这对某人有一点帮助。

        $original_filename = $_FILES["myfile"]["name"];
        if(file_exists($output_dir.$original_filename))
        {
            $filename_only = substr($original_filename, 0, strrpos($original_filename, "."));
            $ext = substr($original_filename, strrpos($original_filename, "."));
            $fn = $filename_only.$ext;
            $i=1;
            while(file_exists($output_dir.$fn)){
               $fn=$filename_only.'_'.$i.$ext;
               $i++;
            }
        }
        else
        {
            $fn = $original_filename;
        }
<?php
$base_name = 'blah-';
$extension = '.php';
while ($counter < 1000 ) {
    $filename = $base_name . $counter++ . $extension; 
    if ( file_exists($filename) ) continue;
}
$fh = fopen($filename, "a");
fwrite($fh, $text);
fclose($fh);