note 57338 deleted from features.file-upload by mazzanet
| From: | mazzanet@php.net | Date: | Fri, 30 Sep 2005 20:46:48 +0000 |
| Subject: | note 57338 deleted from features.file-upload by mazzanet | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-96098@lists.php.net to get a copy of this message | ||
Note Submitter: mark meves (mavis)
----
A recurring theme on this page is that of generating a unique name for your uploaded file. Almost
every comment suggests using the time() function. *Do not* use this function alone.
The function time() generates seconds from unix epoch which is the number of seconds that have
elapsed since some moment in 1970 when the first unix nerd was born or lost his virginity or
something. It is certainly possible, because of all the totally awesome photo CMS's that
everyone is obviously busy writing, that your popular site will get more than one uploaded file
within a second of each other?
I have 3 suggestions in descending order of robustitude or whatever:
1) Use a blob field in a database. This is documented elsewhere. (no need to generate a name--
auto_increment)
2) do{
$sNewPath = $this->generateAName();
}while(!file_exists($sNewPath));
3) what we did -- using microtime() instead (milliseconds). Although the likelyhood of this
breaking increases as we approach having millions of users uploading files within the same second.
(It's a popular site, you see.)
/*
@param sOrigName e.g. "timesheet-2005-06-05.xls"
@return e.g. 29183749248.2948729847.xls
sets msec and sec, too.
with no file extension, the resultant name will
have a trailing dot.
we like the idea of the name being unique but
meaningful, so we stamp it with the mircotime.
is there a small chance of clobber? __FIXME__
*/
function generateNewUniqueName($sOrigName,&$sec=null,&$msec=null)
{
$aInfo = pathinfo($sOrigName);
$ext = $aInfo['extension'];
// microtime returns "msec sec" we want "sec.msec"
list($msec,$sec) = explode(' ',microtime());
// chop of the leading "0." on the microseconds
if(!preg_match('/^0\.(\d+)$/',$msec,$matches)){
throw new JEL_Exception("regex failure");
}
$msec = $matches[1];
$sRet = "$sec.$msec.$ext";
return $sRet;
}
-code till dawn!
my email is my first name dot last name at gmail dot com