PHP中的唯一和临时文件名? [英] Unique and temporary file names in PHP?

查看:69
本文介绍了PHP中的唯一和临时文件名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将一些文件转换为PDF,然后将它们附加到电子邮件中.我使用Pear Mail作为电子邮件的一部分,这很好(大多数情况下-仍在解决一些问题),但是作为此过程的一部分,我需要创建临时文件.现在,我可以使用 tempnam()函数,但这听起来像是在创建文件系统上的文件,这不是我想要的.

I need to convert some files to PDF and then attach them to an email. I'm using Pear Mail for the email side of it and that's fine (mostly--still working out some issues) but as part of this I need to create temporary files. Now I could use the tempnam() function but it sounds like it creates a file on the filesystem, which isn't what I want.

我只想在临时文件系统中使用一个名称(使用

I just want a name in the temporary file system (using sys_get_temp_dir()) that won't clash with someone else running the same script of the same user invoking the script more than once.

建议?

推荐答案

我过去曾经使用uniqid()生成唯一的文件名,但实际上并未创建文件.

I've used uniqid() in the past to generate a unique filename, but not actually create the file.

$filename = uniqid(rand(), true) . '.pdf';

第一个参数可以是您想要的任何参数,但是我在这里使用rand()使其更加随机.使用设置的前缀,可以进一步避免与系统中的其他临时文件冲突.

The first parameter can be anything you want, but I used rand() here to make it even a bit more random. Using a set prefix, you could further avoid collisions with other temp files in the system.

$filename = uniqid('MyApp', true) . '.pdf';

从那里,您只需创建文件.如果其他所有方法均失败,则将其置于while循环中,并继续生成它,直到获得可行为止.

From there, you just create the file. If all else fails, put it in a while loop and keep generating it until you get one that works.

while (true) {
 $filename = uniqid('MyApp', true) . '.pdf';
 if (!file_exists(sys_get_temp_dir() . $filename)) break;
}

这篇关于PHP中的唯一和临时文件名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆