10

How would I go about creating a random string of text for use with file names?

I am uploading photos and renaming them upon completion. All photos are going to be stored in one directory so their filenames need to be unique.

Is there a standard way of doing this?

Is there a way to check if the filename already exists before trying to overwrite?

This is for a single user environment (myself) to show my personal photos on my website however I would like to automate it a little. I don't need to worry about two users trying to upload and generating the same filename at the same time but I do want to check if it exists already.

I know how to upload the file, and I know how to generate random strings, but I want to know if there is a standard way of doing it.

2
  • Have you tried anything ? Please post what you have you done. Commented Sep 29, 2013 at 20:56
  • see this question Commented Sep 29, 2013 at 20:57

3 Answers 3

41

The proper way to do this is to use PHP's tempnam() function. It creates a file in the specified directory with a guaranteed unique name, so you don't have to worry about randomness or overwriting an existing file:

$filename = tempnam('/path/to/storage/directory', '');
unlink($filename);
move_uploaded_file($_FILES['file']['tmp_name'], $filename);
Sign up to request clarification or add additional context in comments.

3 Comments

how could I use your code in conjunction with that of Domecraft's? I want to have longer file names.
You could use @Domecraft's code to generate a random string, then pass it as the second argument to tempnam(). It would then be prefixed to the file name.
That's true, but you introduce a problem by unlink()ing it. If unique file names are required for security, this might not be ok.
32
function random_string($length) {
    $key = '';
    $keys = array_merge(range(0, 9), range('a', 'z'));

    for ($i = 0; $i < $length; $i++) {
        $key .= $keys[array_rand($keys)];
    }

    return $key;
}

echo random_string(50);

Example output:

zsd16xzv3jsytnp87tk7ygv73k8zmr0ekh6ly7mxaeyeh46oe8

EDIT

Make this unique in a directory, changes to function here:

function random_filename($length, $directory = '', $extension = '')
{
    // default to this files directory if empty...
    $dir = !empty($directory) && is_dir($directory) ? $directory : dirname(__FILE__);

    do {
        $key = '';
        $keys = array_merge(range(0, 9), range('a', 'z'));

        for ($i = 0; $i < $length; $i++) {
            $key .= $keys[array_rand($keys)];
        }
    } while (file_exists($dir . '/' . $key . (!empty($extension) ? '.' . $extension : '')));

    return $key . (!empty($extension) ? '.' . $extension : '');
}

// Checks in the directory of where this file is located.
echo random_filename(50);

// Checks in a user-supplied directory...
echo random_filename(50, '/ServerRoot/mysite/myfiles');

// Checks in current directory of php file, with zip extension...
echo random_filename(50, '', 'zip');

6 Comments

Thank you, this is exactly what I was after. I've done it in the past but wasn't sure if this would be 'robust' enough.
I tried to straight away but I had to leave it a few minutes. It's done now.
This solution doesn't guarantee uniqueness - the string generation doesn't take into account existing files.
Yes, but he doesn't have to know that.
You need some context - otherwise there's nothing to compare against to ensure uniqueness. That's why the tempnam() function requires a directory :)
|
1

Hope this is what you are looking for:-

<?php
function generateFileName()
{
$chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ123456789_";
$name = "";
for($i=0; $i<12; $i++)
$name.= $chars[rand(0,strlen($chars))];
return $name;
}
//get a random name of the file here
$fileName = generateName();
//what we need to do is scan the directory for existence of the current filename
$files = scandir(dirname(__FILE__).'/images');//assumed images are stored in images directory of the current directory
$temp = $fileName.'.'.$_FILES['assumed']['type'];//add extension to randomly generated image name
for($i = 0; $i<count($files); $i++)
  if($temp==$files[$i] && !is_dir($files[$i]))
   {
     $fileName .= "_1.".$_FILES['assumed']['type'];
     break;
   }
 unset($temp);
 unset($files);
 //now you can upload an image in the directory with a random unique file name as you required
 move_uploaded_file($_FILES['assumed']['tmp_name'],"images/".$fileName);
 unset($fileName);
?>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.