how to create random name for a file ?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
aneuryzma
Forum Contributor
Posts: 106
Joined: Sat May 17, 2008 7:03 am

how to create random name for a file ?

Post 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
User avatar
pickle
Briney Mod
Posts: 6445
Joined: Mon Jan 19, 2004 6:11 pm
Location: 53.01N x 112.48W
Contact:

Re: how to create random name for a file ?

Post 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.
Real programmers don't comment their code. If it was hard to write, it should be hard to understand.
aneuryzma
Forum Contributor
Posts: 106
Joined: Sat May 17, 2008 7:03 am

Re: how to create random name for a file ?

Post 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!
User avatar
pickle
Briney Mod
Posts: 6445
Joined: Mon Jan 19, 2004 6:11 pm
Location: 53.01N x 112.48W
Contact:

Re: how to create random name for a file ?

Post 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.
Real programmers don't comment their code. If it was hard to write, it should be hard to understand.
Post Reply