Create a temp file with a specific extension using php
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;
}
my way is using tempnam
$file = tempnam(sys_get_temp_dir(), 'prefix');
file_put_contents($file.'.extension', $data);
{
//use your file
}
unlink($file);//to delete an empty file that tempnam creates
unlink($file.'.extension');//to delete your file
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');
This might simulate mkstemp()
(see http://linux.die.net/man/3/mkstemp) a bit, achieving what you want to do:
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);
}