1

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

4 回答 4

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

尽管如此,这个解决方案的方向并不能很好地扩展。你不想file_exists经常检查超过 100 个。

于 2011-10-20T01:29:12.750 回答
2

使用带有计数器变量的 while 循环$i。继续递增计数器,直到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);
于 2011-10-20T01:30:09.963 回答
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;
        }
于 2014-03-07T15:27:42.157 回答
-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);
于 2011-10-20T01:29:16.813 回答