使用 php 创建具有特定扩展名的临时文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8970913/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Create a temp file with a specific extension using php
提问by nikhil
采纳答案by mobius
This might simulate mkstemp()
(see http://linux.die.net/man/3/mkstemp) a bit, achieving what you want to do:
这可能会模拟mkstemp()
(参见http://linux.die.net/man/3/mkstemp),实现您想要做的事情:
function mkstemp( $template ) {
$attempts = 238328; // 62 x 62 x 62
$letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
$length = strlen($letters) - 1;
if( mb_strlen($template) < 6 || !strstr($template, 'XXXXXX') )
return FALSE;
for( $count = 0; $count < $attempts; ++$count) {
$random = "";
for($p = 0; $p < 6; $p++) {
$random .= $letters[mt_rand(0, $length)];
}
$randomFile = str_replace("XXXXXX", $random, $template);
if( !($fd = @fopen($randomFile, "x+")) )
continue;
return $fd;
}
return FALSE;
}
So you could do:
所以你可以这样做:
if( ($f = mkstemp("test-XXXXXX.txt")) ) {
fwrite($f, "test\n");
fclose($f);
}
回答by nathan hayfield
Easiest way i have found is to create tempfile and then just rename it. For example:
我发现的最简单的方法是创建临时文件,然后重命名它。例如:
$tmpfname = tempnam(sys_get_temp_dir(), "Pre_");
rename($tmpfname, $tmpfname .= '.pdf');
回答by Yasmany Hernandez Hernandez
回答by Georg
public static function makeTempFileInFolder($prefix, $suffix, $folder="")
{
if (strlen($folder)==0) $folder = sys_get_temp_dir();
do {
$file = $folder."/".$prefix.rand(1,99999).time().$suffix;
} while (file_exists($file));
return $file;
}
回答by Lobo
Maybe using
也许使用
move_uploaded_file($tmp_name, "$uploads_dir/$name.myextension");
move_uploaded_file($tmp_name, "$uploads_dir/$name.myextension");
See http://php.net/manual/en/function.move-uploaded-file.php#example-2209
见http://php.net/manual/en/function.move-uploaded-file.php#example-2209