Php 检查文件名是否存在,以及

Php 检查文件名是否存在,以及,php,Php,我想知道是否有办法检查文件名是否存在,然后在其后面添加一个数字,我知道这一点-在基本的for中是可能的,因此如果有人这样做一次,它将在其后面添加1 但是,你如何让它检查是否有人做过不止一次呢?那么第一次它会添加一个1然后是2然后是3等等 $title = $_POST['title']; $content = $_POST['content']; $compile = $title. "\r\n" .$content; $content = $compile; $path = "../data/

我想知道是否有办法检查文件名是否存在,然后在其后面添加一个数字,我知道这一点-在基本的for中是可能的,因此如果有人这样做一次,它将在其后面添加
1

但是,你如何让它检查是否有人做过不止一次呢?那么第一次它会添加一个
1
然后是
2
然后是
3
等等

$title = $_POST['title'];
$content = $_POST['content'];
$compile = $title. "\r\n" .$content;
$content = $compile;
$path = "../data/" .md5($title). ".txt";
$fp = fopen($path,"wb");
fwrite($fp,$content);
fclose($fp);

$con=new mysqli("###","###_public","###","###"); 
if (!($stmt = $con->prepare("INSERT INTO `blog_posts` (`post_title`,`post_content`,`post_date`) VALUES (?,?,?)")) || !is_object($stmt)) {
    die( "Error preparing: (" .$con->errno . ") " . $con->error);
}
$stmt->bind_param('sss', $_POST['title'], $path, $_POST['date']);
if($stmt->execute()) { 
    echo "Successfully Posted";
} else {
    echo "Unsuccessfully Posted";
}
    $stmt->close();

感谢您提前提供的帮助

总体思路如下:

$basefilename = "somefile";
$filename = $basefilename;
$i = 0;
while(file_exists("../data/".$filename.".txt") $filename = $basefilename.(++$i);
<?php
if(file_exists($filename)) { // check if the file exists in the first place
   $i = 1;
   while(file_exists($filename.$i)) { // check if the filename with the index exists. If so, increase the $i by 1 and try again
      $i++;
   }
   rename($filename, $filename.$i); // rename the actual file
} else {
   // file did not exist in the first place
}

根据需要进行调整。

您可以使用以下内容:

$basefilename = "somefile";
$filename = $basefilename;
$i = 0;
while(file_exists("../data/".$filename.".txt") $filename = $basefilename.(++$i);
<?php
if(file_exists($filename)) { // check if the file exists in the first place
   $i = 1;
   while(file_exists($filename.$i)) { // check if the filename with the index exists. If so, increase the $i by 1 and try again
      $i++;
   }
   rename($filename, $filename.$i); // rename the actual file
} else {
   // file did not exist in the first place
}

  • 不要在文件名的末尾添加字符串-最终 很快就会达到操作系统文件名长度限制。你也会失败 当字符串太大时,识别最后添加的数字- 你必须从一开始就解析所有的数字
  • 用于搜索文件名
  • 解析在末尾和增量处为数字找到的文件名 那个号码
  • 在文件名上使用,并检查返回状态 避免赛车条件
  • 通常避免这种情况-使用数据库或任何其他系统 支持原子操作

  • PHP有一个内置的函数来检查文件是否存在-为什么不等到你运行了
    insert
    之后再使用
    blog_posts
    的唯一id作为文件名,这样你就知道它是唯一的,并且很容易检索文件。我以前就是这么做的,但它有点违反了DRY,因为有两个
    文件\u存在
    调用;)