PHP - Unique name for uploaded files?

Discussion in 'Web Design and Development' started by floyde, May 19, 2006.

  1. floyde macrumors 6502a

    floyde

    Joined:
    Apr 7, 2005
    Location:
    Monterrey, México
    #1
    Can I create a unique filename for user uploaded images using PHP's uniqid function? Will it do? or is there a risk of overwriting an exisitng image?

    I also found this on the PHP manual, maybe it's less risky:
    PHP:
    <?php
    // no prefix
    $token md5(uniqid());

    // better, difficult to guess
    $better_token md5(uniqid(rand(), true));
    ?>
    thanks
     
  2. ac2102 macrumors member

    ac2102

    Joined:
    May 12, 2003
    Location:
    Bristol - England
    #2
    Could you not just do a check to see if the filename is already used?

    You could use

    PHP:
    file_exists("./path/to/file.jpg")
    in an if or while statement to keep creating new names.

    Having said that, i am only making this suggestion as i do not know the answer to your previous question! The methods you described would make the possibility of producing the same file name extremely small, but i don't know exactly how small!

    Sorry if my answer seems a little vague, but that is the best i have for now!

    Good luck with your project,

    ac2102
     
  3. floyde thread starter macrumors 6502a

    floyde

    Joined:
    Apr 7, 2005
    Location:
    Monterrey, México
    #3
    Thanks, that will definately work. I'm still wondering if that's the standard way of doing it though.
     
  4. c-Row macrumors 65816

    c-Row

    Joined:
    Jan 10, 2006
    Location:
    Germany
    #4
    Another way would be to append/prepend the current timestamp. Works fine for us.
     
  5. ac2102 macrumors member

    ac2102

    Joined:
    May 12, 2003
    Location:
    Bristol - England
    #5
    Good thinking with the timestamp. Never used that for filenames, but will now!

    Top choice,

    ac2102
     
  6. Thom_Edwards macrumors regular

    Joined:
    Apr 11, 2003
    #6
    my vote is the session id concatenated with a timestamp.
     
  7. c-Row macrumors 65816

    c-Row

    Joined:
    Jan 10, 2006
    Location:
    Germany
    #7
    Now I guess that should be unique enough... :D
     
  8. floyde thread starter macrumors 6502a

    floyde

    Joined:
    Apr 7, 2005
    Location:
    Monterrey, México
    #8
    Yes, I think we have a winner ;)
     

Share This Page