使用 PHP 脚本自动创建文件
我有一个项目需要使用 php 中的 fwrite 创建文件。我想做的是使其通用,我想让每个文件都是唯一的并且不要覆盖其他文件。 我正在创建一个项目,它将记录 php 表单中的文本并将其保存为 html,所以我想输出生成 generated-file1.html 和 generated-file2.html 等。谢谢。
I have a project that needs to create files using the fwrite in php. What I want to do is to make it generic, I want to make each file unique and dont overwrite on the others.
I am creating a project that will record the text from a php form and save it as html, so I want to output to have generated-file1.html and generated-file2.html, etc.. Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这将为您提供给定目录中 html 文件数量的计数
,然后您的新文件名将类似于:
然后使用
$ generated_file_name
fwrite虽然我最近不得不做类似的事情并使用 uniq 代替。像这样:
This will give you a count of the number of html files in a given directory
and then your new filename will be something like:
and then fwrite using
$generated_file_name
Although I've had to do a similar thing recently and used uniq instead. Like this:
我建议使用时间作为文件名的第一部分(因为这应该会导致文件按时间/字母顺序列出,然后借用 @TomcatExodus 来提高文件名唯一的机会(如果两个提交是 generated_file
这将产生如下文件名:
I would suggest using the time as the first part of the filename (as that should then result in files being listed in chronological/alphabetic order, and then borrow from @TomcatExodus to improve the chances of the filename being unique (incase of two submissions being simultaneous).
This would produce filenames like:
如果您想绝对确保不会覆盖现有文件,您可以附加 uniqid( ) 到文件名。如果您希望它是连续的,则必须从文件系统读取现有文件并计算下一个增量,这可能会导致 IO 开销。
我会使用 uniqid() 方法:)
If you want to make absolutely sure that you will not overwrite an existing file you could append a uniqid() to the filename. If you want it to be sequential you'll have to read existing files from your filesystem and calculate the next increment which can result in an IO overhead.
I'd go with the uniqid() method :)
如果您的实现每次都会产生唯一的表单结果(因此是唯一的文件),您可以将表单数据散列到文件名中,为您提供唯一的路径,以及快速筛选重复项的机会;
If your implementation should result in unique form results every time (therefore unique files) you could hash form data into a filename, giving you unique paths, as well as the opportunity to quickly sort out duplicates;
做这样的事情:
Do something like this: