2011-03-14 38 views
0

我有一個需要使用php中的fwrite創建文件的項目。我想要做的是使其通用,我想讓每個文件都是唯一的,而不要覆蓋其他文件。 我正在創建一個項目,將記錄從一個PHP窗體中的文本,並將其保存爲HTML,所以我想要輸出具有generated-file1.html和generated-file2.html等。謝謝。使用PHP腳本自動創建文件

回答

0

如果您想確保不會覆蓋現有文件,您可以將uniqid()添加到文件名中。如果你希望它是連續的,你必須從你的文件系統中讀取現有的文件並計算下一個可能導致IO開銷的增量。

我會去與uniqid()方法:)

+0

只是一個快速的感嘆詞 - 如果他們想要的文件名是連續的(雖然不使用遞增計數器),你可以使用'time()'返回Unix時間(應該是順序的),然後追加'uniqid()'以提高避免衝突的機率。 – 2011-03-14 06:05:51

-1

做這樣的事情:

$i = 0; 
while (file_exists("file-".$i.".html")) { 
$i++; 
} 
$file = fopen("file-".$i.".html"); 
+0

雖然這確實可行,但可能需要很長時間才能找到下一個可用號碼。例如,如果表單被提交了1,000次,那麼這個代碼會在發現下一個可用的數字之前執行'while()'循環1000次。 @ Emmanuel的解決方案會更快 - 它會查找名稱與指定模式匹配的文件數量,然後將該數字加1。同樣的結果,但從長遠來看肯定會更快。 – 2011-03-14 06:03:33

1

這會給你的HTML文件數的計數在給定的目錄

$filecount = count(glob("/Path/to/your/files/*.html")); 

,然後你的新的文件名會是這樣的:

$generated_file_name = "generated-file".($filecount+1).".html"; 

然後用fwrite使用$generated_file_name

儘管最近我不得不做類似的事情,而是使用uniq代替。就像這樣:

$generated_file_name = md5(uniqid(mt_rand(), true)).".html"; 
+0

好的答案 - 確切地說是OP所要求的,並且還提供了一個備用選項。 – 2011-03-14 06:06:48

0

如果您的實現應該每次(因此獨特的文件),你可以散列表單數據到一個文件名,給你獨特的路徑,以及有機會迅速理清重複導致獨特的形式結果;

// capture all posted form data into an array 
// validate and sanitize as necessary 
$data = $_POST; 

// hash data for filename 
$fname = md5(serialize($data)); 

$fpath = 'path/to/dir/' . $fname . '.html'; 

if(!file_exists($fpath)){ 

    //write data to $fpath 

} 
1

我會建議使用時間作爲文件名的第一部分(如應該然後導致文件按時間/字母順序被列,然後從@TomcatExodus藉以提高文件名存在的機會唯一的(櫃面兩個提交是同時的)

<?php 
$data = $_POST; 
$md5 = md5($data); 
$time = time(); 
$filename_prefix = 'generated_file'; 
$filename_extn = 'htm'; 

$filename = $filename_prefix.'-'.$time.'-'.$md5.'.'.$filename_extn; 

if(file_exists($filename)){ 
# EXTREMELY UNLIKELY, unless two forms with the same content and at the same time are submitted 
    $filename = $filename_prefix.'-'.$time.'-'.$md5.'-'.uniqid().'.'.$filename_extn; 
# IMPROBABLE that this will clash now... 
} 

if(file_exists($filename)){ 
# Handle the Error Condition 
}else{ 
    file_put_contents($filename , 'Whatever the File Content Should Be...'); 
} 

這將產生象文件名:

  • generated_file-1300080525-46ea0d5b246d2841744c26f72a86fc29.htm
  • generated_file-1300092315-5d350416626ab6bd2868aa84fe10f70c.htm
  • generated_file-1300109456-77eae508ae79df1ba5e2b2ada645e2ee.htm