繁体   English   中英

使用PHP脚本自动创建文件

[英]Create Files Automatically using PHP script

我有一个项目需要使用php中的fwrite创建文件。 我要做的是使其通用,我要使每个文件都唯一,并且不要覆盖其他文件。 我正在创建一个项目,该项目将记录来自php形式的文本并将其另存为html,因此我想输出包含generate-file1.html和generate-file2.html等的内容。谢谢。

这将为您提供给定目录中的html文件数

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

然后您的新文件名将类似于:

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

然后使用$generated_file_name generation_file_name fwrite

尽管最近我不得不做类似的事情,而改用uniq。 像这样:

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

我建议使用时间作为文件名的第一部分(因为这将导致文件按时间顺序/字母顺序列出,然后从@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...' );
}

这将产生如下文件名:

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

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

我会用uniqid()方法:)

如果您的实现每次都产生唯一的表单结果(因此是唯一的文件),则可以将表单数据散列到文件名中,从而为您提供唯一的路径,并有机会快速整理出重复项;

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

}

做这样的事情:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM