如果该文件名已存在,请将数字添加到fopen链接

时间:2011-10-20 01:21:00

标签: 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");
    fwrite($fh, $text);
}
fclose($fh);

4 个答案:

答案 0 :(得分:2)

我在这样的场景中使用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

答案 1 :(得分:2)

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

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

答案 2 :(得分:0)

我正在寻找类似的东西,并根据我的需求扩展了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;
        }

答案 3 :(得分:-1)

<?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);
相关问题