My idea is like if there is a exist file , add the filename to filename.(1).html and so on,
here is my code.But I can not figure out how to check the file name if exist have (number)
.
So how to check it and append a (1)… if that is exist?
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.1 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
</head>
<body>
<?php
session_start();
if($_SERVER['REQUEST_METHOD'] == "POST"){
$editorData = $_POST[ 'editor1' ];
$fileName = $_POST[ 'tname' ];
$uid= $_SESSION['username'];
$filePath ="../template/".$uid."/";
$myFile = $fileName.".html";
if (!file_exists($filePath)) {
mkdir($filePath, 0755);
}
if (file_exists($filePath.$myFile)) {
$myFile = $fileName."(".$num.")".html";
}
$fh = fopen($filePath.$myFile, 'w') or die("Can not open file");
fwrite($fh, $editorData);
fclose($fh);
echo "You have created a template. You can close this tab now";
}
?>
</body>
</html>
You can use glob to find all files matching your filename and the following number, you could then count those files to figure out what the next file should be named.
Since your first file does not follow the same naming scheme as the following, you have to count that one for it self.
Be aware that if you allow deletion of the files, this will not work, as the count of existing files is no longer guaranteed to be equal to the highest number in the list.