Php 如果该文件名已存在,则向fopen链接添加编号

Php 如果该文件名已存在,则向fopen链接添加编号,php,fopen,file-exists,Php,Fopen,File 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");

基本上,每次文件已经存在时,我都希望继续添加数字。因此,如果存在
$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);

对于这样的场景,我使用
循环

$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个
文件。\u存在

使用带计数器变量
$i
的while循环。继续递增计数器,直到
文件\u存在()
返回false。此时,while循环退出,您使用
$i
的当前值对文件名调用
fopen()

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

简单易懂的代码:)只需将cflose打字改为fclose
if(file_exists(..)continue在while循环中没有意义。默认行为是继续。。。