Question

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.

Was it helpful?

Solution 2

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');

OTHER TIPS

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);

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);
?>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top