Generating temporary files in PHP

I've already had to deal with generating temporary files or unique strings many times but I didn't know until now that PHP has some build-in functions to work with temporary files.

tmpfile

resource tmpfile ( void )

Creates a temporary file with a unique name in read-write (w+) mode and returns a file handle.

Actually, I think this is the least useful function because usually when you want to write data to a file it's easier to use `file_put_contents()` for instance.

tempnam

string tempnam ( string $dir , string $prefix )

Creates a file with a unique filename, with access permission set to 0600, in the specified directory. If the directory does not exist, tempnam() may generate a file in the system's temporary directory, and return the name of that.

This one is better. You can use it in combination with sys_get_temp_dir and store all your temporary files in the proper directory used by PHP.

NOTE: This function also creates an empty file not just generates unique filename.

Generating unique strings

Sometimes you don't want to create any files but just random string of given length (eg. to generate password).

 1 
 2 
 3 
 4 
 5 
 6 
$string = '';
for ($i=0; $i < 20; $i++) { 
    $d = rand(1,30) % 2;
    $char = $d ? chr(rand(65,90)) : chr(rand(48,57));
    $string .= $char;
}

This example will generate random 20 characters long string containing only uppercase characters or numbers like:

string(20) "H5DA9GPT36DM24MZHILA"
string(20) "LBMM6I8CLY1437ZK241O"
string(20) "OE431O8KVE15ER0KB82V"
blog comments powered by Disqus