我想知道是否有办法检查文件名是否存在,然后在它之后添加一个数字,我知道这一点 - 在基本的情况下是可能的,所以如果有人这样做,它会添加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();
感谢您提前提供任何帮助
答案 0 :(得分:1)
一般的想法是这样的:
$basefilename = "somefile";
$filename = $basefilename;
$i = 0;
while(file_exists("../data/".$filename.".txt") $filename = $basefilename.(++$i);
根据需要进行调整。
答案 1 :(得分:1)
您可以使用以下内容:
<?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
}
答案 2 :(得分:0)