使用PHP脚本自动创建文件

时间:2011-03-14 01:18:53

标签: php html forms fwrite

我有一个需要使用php中的fwrite创建文件的项目。我想要做的是使它通用,我想让每个文件都独一无二,不要覆盖其他文件。 我正在创建一个项目,将从PHP表单中记录文本并将其保存为html,所以我想输出生成文件_html和generated-file2.html等等。谢谢。

5 个答案:

答案 0 :(得分:1)

这将为您计算给定目录中的html文件数

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

然后您的新文件名将是:

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

然后使用$generated_file_name

进行fwrite

虽然我最近不得不做类似的事情而是使用uniq。像这样:

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

答案 1 :(得分: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

答案 2 :(得分:0)

如果您想确保不会覆盖现有文件,可以在文件名后附加uniqid()。如果您希望它是顺序的,则必须从文件系统中读取现有文件并计算可能导致IO开销的下一个增量。

我选择了uniqid()方法:)

答案 3 :(得分: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

}

答案 4 :(得分:-1)

做这样的事情:

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