2012-03-21 11 views
0

私の考えは、存在するファイルがあるかのように、ファイル名にfilenameを付け加えるようなものです。(1).htmlなど、 は私のコードです。しかし、もし存在すればファイル名を調べる方法は分かりません番号) 。 これを確認し、(1)...があれば追加するには?あなたがあなたのファイル名と、次の番号に一致するすべてのファイルを検索しglobを使用することができますファイル名がフォルダに存在する場合、phpを使ってIDを追加しますか?

<!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> 

答えて

1

、あなたは、次のファイルが命名されなければならないかを把握するために、それらのファイルを数えることができます。

最初のファイルは、次のような命名規則に従っていないため、1つのファイルはそれ自身のためにカウントする必要があります。

// Check if a file with the exact name exists 
if(file_exists($filePath.$myFile)){ 
    // It does - the next number should be 1 
    $num = 1; 
    // Check how many more files with the name followed by a number exists 
    $existingFiles = glob($filePath.$fileName.'([0-9]*).html'); 
    $num += count($existingFiles); 
    // Create the new name of the file 
    $myFile = $fileName."(".$num.")".html"; 
} 

既存のファイルの数はもはや、リスト内の最高数と同じであることが保証されて、あなたはファイルの削除を許可した場合、これが動作しないことに注意してくださいません。

関連する問題