Page 1 of 1

how to create random name for a file ?

Posted: Thu May 07, 2009 2:04 pm
by aneuryzma
Hi,

how can I create a random name to store my file into the server ?

Code: Select all

$safe_filename = str_replace('/', '', $_FILES['file']['name']);
$safe_filename = str_replace('..', '', $safe_filename);
$safe_filename = .. random name... + $safe_filename;
Should I create a random number ?

thanks

Re: how to create random name for a file ?

Posted: Thu May 07, 2009 2:17 pm
by pickle
Something like this could work:

Code: Select all

function createRandom($length=8)
{
  $allowed = 'abcdefghijklmnopqrstuvwxyz1234567890';
  for($i=0;$i<$length;$i++)
  {
    $ret_val .= $allowed[rand(0,strlen($allowed))];
  }
  return $ret_val;
}
However, there's no guarantee that the file won't already exist. You could add the time with microseconds on that to reduce the chances significantly, but the only way to guarantee each random string is also unique, you'll need to do a check - either against the filesystem or a database of all files, to check that the random string doesn't already exist.

Re: how to create random name for a file ?

Posted: Thu May 07, 2009 2:30 pm
by aneuryzma
ok, so.. how can I check ? should I scan all the files everytime ?

how can I do it in php ?

ps. I store the url to the files in mysql, so probably it is better to scan mysql to check.

Any hint on the code is really appreciated!

Re: how to create random name for a file ?

Posted: Thu May 07, 2009 5:10 pm
by pickle
You can generate the filename, then do a file_exists() on that filename. I'm not sure, but that might be less costly than doing a database query.