It's useful to be able to create unique filenames once
in a while.
If you want good portability so your code will work on
a Windoze box as well as a Linny server then you get
stuffed by not being able to access the PID of the
server process - this is the root of many unique
file naming systems.
Below is a little function that works on anything that
runs PHP.
The idea here is to get the IP of the remote client and
use that as the basis of a unique filename. There is a
possible problem in that of the remote is using a shared,
NAT, Internet feed then you can quite conceivably get
multiple requests that would end up with the same IP.
If we also use the current microtime() then the chances
of two requests generating the same unique become as
close to zero as you can get.
<?php
function unique_filename($xtn = ".tmp")
{
// explode the IP of the remote client into four parts
$ipbits = explode(".", $_SERVER["REMOTE_ADDR"]);
// Get both seconds and microseconds parts of the time
list($usec, $sec) = explode(" ",microtime());
// Fudge the time we just got to create two 16 bit words
$usec = (integer) ($usec * 65536);
$sec = ((integer) $sec) & 0xFFFF;
// Fun bit - convert the remote client's IP into a 32 bit
// hex number then tag on the time.
// Result of this operation looks like this xxxxxxxx-xxxx-xxxx
$uid = sprintf("%08x-%04x-%04x",($ipbits[0] << 24)
| ($ipbits[1] << 16)
| ($ipbits[2] << 8)
| $ipbits[3], $sec, $usec);
// Tag on the extension and return the filename
return $uid.$xtn;
}
?>