/    Sign up×
Community /Pin to ProfileBookmark

[RESOLVED] File Upload Generate a name

I have a form where I upload a file. I would like to create a RANDOM name for all the files uploaded that does not repeat….yet only about 10-20 alpha-numeric combination long. Also.. I need to get the .extention off of the file so I know what kind is uploaded to attach to the end of the name. What is the best way to go about this?

basically I have me_and_her.jpg

I upload the file

then want a random_name.jpg to save it to my server.

to post a comment
PHP

19 Comments(s)

Copy linkTweet thisAlerts:
@sitehatcheryAug 11.2006 — Here's a very rough outline of one way to approach this:

  • 1. read the extension off of the filename.

  • 2. generate a random name.

  • 3. attach the file extension to the random name that contains 10-20 alpha-numeric characters

  • 4. read through the file upload directory.

  • 5. compare each file in the upload directory with the generated random name.

  • 6. if a match exists, go back to step 2.

  • 7. if a match does not exist, you're in luck. Use the randomly generated name.


  • Another option is to read all the files into an array. Then use the in_array() function to see if the auto generated file name + extension exists in the array. If it exists, generate another number.

    There may be a more efficient way of doing it, but hopefully this gets some dialog on the subject going.
    Copy linkTweet thisAlerts:
    @PineSolPirateAug 11.2006 — Here's the code I use for this sort of thing.
    [code=php]$extension = $_FILES['document']['name']{strlen($_FILES['documentField']['name'])-3};

    $target = "/path/to/files/";
    $target .= rand(0, 100000);
    $target .= $extension;

    while (file_exists($target))
    {
    $target = "/path/to/files/";
    $target .= rand(0, 100000);
    $target .= $extension;
    }
    move_uploaded_file($_FILES['documentField']['tmp_name'],$target);[/code]

    Should be good for about 100000 files.

    This should be more efficient since you only have to check the filename a few times before you get a match.
    Copy linkTweet thisAlerts:
    @PineSolPirateAug 11.2006 — I also bet you could use [url=http://us3.php.net/manual/en/function.md5-file.php]MD5_file[/url] for nice, unique names that will alert you to duplicate uploads. That'd be even better!
    Copy linkTweet thisAlerts:
    @firmanauthorAug 11.2006 — Thank you for these suggestions so far... How about a random 10-20 digit alpha-numeric name?
    Copy linkTweet thisAlerts:
    @sitehatcheryAug 11.2006 — [code=php]
    $ranLen=rand(10,20);
    $getVal ="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    $ranFileName="";
    for ($i=1; $i<=$ranLen; $i++) {
    $ranFileName.= substr($getVal, rand(0,(strlen($getVal)-1)), 1);
    $ranFileName.=$extension;
    }
    [/code]
    Copy linkTweet thisAlerts:
    @sitehatcheryAug 11.2006 — Will this work for you?
    [code=php]
    $extension = $_FILES['document']['name']{strlen($_FILES['documentField']['name'])-3};
    $target = "/path/to/files/";

    function randomFile($extension, $target){
    $ranLen=rand(10,20);
    $getVal ="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    $ranFileName="";
    for ($i=1; $i<=$ranLen; $i++) {
    $ranFileName.= substr($getVal, rand(0,(strlen($getVal)-1)), 1);
    $file=$target.$ranFileName.$extension;
    }

    if(file_exists($file)){
    randomFile($extension, $target);
    }
    else{
    return $file;
    }

    }

    move_uploaded_file($_FILES['documentField']['tmp_name'], randomFile($extension, $target));
    [/code]
    Copy linkTweet thisAlerts:
    @bokehAug 11.2006 — I hate random because it causes collisions. Why not just use [I]time()[/I]? It ten digits long and you could upload one file a second between now and 2037 without any chance of running out of file names.
    Copy linkTweet thisAlerts:
    @firmanauthorAug 12.2006 — can you explain the time thing a little further? and why would 2037 collide?
    Copy linkTweet thisAlerts:
    @bokehAug 12.2006 — [code=php]$filename = time() . '.jpg';[/code]

    2037 is when the present timestamping system will run out of numbers.
    Copy linkTweet thisAlerts:
    @sitehatcheryAug 12.2006 — You don't have to worry about collisions with this randomFile() function. With variable number of characters (10-20) with uppercase, lowercase, and numbers in random order, it's very unlikely that a duplicate will occur. In the rare ocassion that a duplicate would occur (better chance of winning the lottery), the function calls itself and is run again.

    Oh, and I'd replace the extension getter code with this function:
    [code=php]
    function getExtension($file){
    $exArray=explode(".", $file);
    $arrCount=count($exArray);
    $extension='.'.$exArray[$arrCount-1];
    return $extension;
    }
    [/code]
    Copy linkTweet thisAlerts:
    @bokehAug 12.2006 — Random filenames are another branch of unmaintainable code. A logical naming convention is always going to be better than leaving your filenames to chance.
    Copy linkTweet thisAlerts:
    @balloonbuffoonAug 12.2006 — Yeah, I use time() for my uploaded filenames, and it gives you an added bonus of knowing exactly when it was uploaded.

    --Steve
    Copy linkTweet thisAlerts:
    @balloonbuffoonAug 12.2006 — And for getting an extension, you can just use this:
    [code=php]$extension = pathinfo($filename, PATHINFO_EXTENSION);[/code]
    --Steve
    Copy linkTweet thisAlerts:
    @NogDogAug 12.2006 — Guess I was bored -- here's a function using microtime to make sure we don't get any duplicates. It also uses getimagesize() if available to determine the image type, if applicable.
    [code=php]
    function unique_file_name($file)
    {
    $suffix = '';
    if(function_exists("getimagesize") and is_readable($file))
    {
    $info = getimagesize($file);
    if($info[2])
    {
    $types = array(1 => 'gif', 'jpg', 'png', 'swf', 'psd', 'bmp', 'tiff',
    'tiff', 'jpc', 'jp2', 'jpx', 'jb2', 'swc', 'iff', 'wbmp', 'xbm');
    $suffix = $types[$info[2]];
    }
    }
    if($suffix == '')
    {
    $name = basename($file);
    $parts = explode(".", $name);
    $suffix = (count($parts) > 1) ? strtolower(array_pop($parts)) : '';
    }
    list($usec, $sec) = explode(' ', microtime());
    $filename = date("YmdHis") . str_replace('0.', '', sprintf("%.6f", $usec));
    $filename .= ($suffix == '') ? '' : ".$suffix";
    return($filename);
    }
    [/code]
    Copy linkTweet thisAlerts:
    @firmanauthorAug 12.2006 — And for getting an extension, you can just use this:
    [code=php]$extension = pathinfo($filename, PATHINFO_EXTENSION);[/code]
    --Steve[/QUOTE]


    How does the above work?
    Copy linkTweet thisAlerts:
    @balloonbuffoonAug 14.2006 — Sorry, late reply, but did you look in the manual for [url=php.net/pathinfo]pathinfo[/url]?

    --Steve
    Copy linkTweet thisAlerts:
    @sitehatcheryAug 15.2006 — I know you're already done, but here is a unique id that is based on the current time. By default it is 23 characters long. if you add 'true' as the second paramenter, it will add an additional 9 characters.

    uniqid(time(), true);
    Copy linkTweet thisAlerts:
    @balloonbuffoonAug 15.2006 — Interesting, I rather like that uniqid() function!

    --Steve
    Copy linkTweet thisAlerts:
    @Phill_PaffordAug 18.2006 — function guid()

    {

    if (function_exists('com_create_guid'))

    {

    return com_create_guid();

    }

    else

    {

    mt_srand((double)microtime()*10000);//optional for php 4.2.0 and up.

    $charid = strtoupper(md5(uniqid(rand(), true)));

    $hyphen = chr(45);// "-"

    $uuid = substr($charid, 0, 8).$hyphen

    .substr($charid, 8, 4).$hyphen

    .substr($charid,12, 4).$hyphen

    .substr($charid,16, 4).$hyphen

    .substr($charid,20,12);

    return $uuid;

    }

    }


    I use this and it works great!
    ×

    Success!

    Help @firman spread the word by sharing this article on Twitter...

    Tweet This
    Sign in
    Forgot password?
    Sign in with TwitchSign in with GithubCreate Account
    about: ({
    version: 0.1.9 BETA 5.19,
    whats_new: community page,
    up_next: more Davinci•003 tasks,
    coming_soon: events calendar,
    social: @webDeveloperHQ
    });

    legal: ({
    terms: of use,
    privacy: policy
    });
    changelog: (
    version: 0.1.9,
    notes: added community page

    version: 0.1.8,
    notes: added Davinci•003

    version: 0.1.7,
    notes: upvote answers to bounties

    version: 0.1.6,
    notes: article editor refresh
    )...
    recent_tips: (
    tipper: @AriseFacilitySolutions09,
    tipped: article
    amount: 1000 SATS,

    tipper: @Yussuf4331,
    tipped: article
    amount: 1000 SATS,

    tipper: @darkwebsites540,
    tipped: article
    amount: 10 SATS,
    )...