我有一个项目需要使用 php 中的 fwrite 创建文件。我想做的是让它通用,我想让每个文件都独一无二,不要覆盖其他文件。我正在创建一个项目,它将记录来自 php 表单的文本并将其保存为 html,所以我想输出生成的文件 1.html 和生成的文件 2.html 等。谢谢。
问问题
4475 次
5 回答
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...' );
}
这将产生如下文件名:
- 生成文件-1300080525-46ea0d5b246d2841744c26f72a86fc29.htm
- 生成文件-1300092315-5d350416626ab6bd2868aa84fe10f70c.htm
- 生成文件-1300109456-77eae508ae79df1ba5e2b2ada645e2ee.htm
于 2011-03-14T05:27:46.333 回答
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";
于 2011-03-14T01:29:14.493 回答
0
如果您想绝对确保不会覆盖现有文件,您可以将uniqid()附加到文件名。如果您希望它是连续的,则必须从文件系统中读取现有文件并计算下一个增量,这可能会导致 IO 开销。
我会使用 uniqid() 方法:)
于 2011-03-14T01:22:05.600 回答
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
}
于 2011-03-14T01:36:58.493 回答
-1
做这样的事情:
$i = 0;
while (file_exists("file-".$i.".html")) {
$i++;
}
$file = fopen("file-".$i.".html");
于 2011-03-14T01:25:00.747 回答