www.webdeveloper.com
Results 1 to 4 of 4

Thread: How do I change the file name if it already exists?

  1. #1
    Join Date
    May 2009
    Location
    Rochester, NY
    Posts
    364

    Question How do I change the file name if it already exists?

    I'm uploading images through PHP. I'm using the following segment of code:

    PHP Code:
        if (file_exists("photos/" $_FILES["file"]["name"]))
          {
          echo 
    $_FILES["file"]["name"] . " already exists. ";
          } 
    What I'd like to do is instead of reporting an error saying the file name already exists, choose a different name for the file that's available. How do I assign a unique name to the file (for example, filename2.jpg, filename3.jpg)? I can do it using what I know about do while loops, but I'm not sure if there's a particularly simple or built-in way.

    Thanks.

  2. #2
    Join Date
    Aug 2004
    Location
    Ankh-Morpork
    Posts
    19,174
    The answer may depend on whether or not you need the actual file name to me semantically meaningful. If not, you could just use uniqid() to create a unique file name, e.g.:
    PHP Code:
    $fileName uniqid(true).'.jpg'
    "Please give us a simple answer, so that we don't have to think, because if we think, we might find answers that don't fit the way we want the world to be."
    ~ Terry Pratchett in Nation

    eBookworm.us

  3. #3
    Join Date
    May 2009
    Location
    Rochester, NY
    Posts
    364
    Sure, semantics aren't a problem. I'll give this a try. Thanks!
    I thought there'd be a built-in way to do this with PHP.

  4. #4
    Join Date
    Aug 2004
    Location
    Ankh-Morpork
    Posts
    19,174
    I believe that the $_FILES['field_name']['tmp_name'] value is similarly constructed via a uniqid-like method, so you could probably just use that (filtered through basename() to strip off the directory portion of the path).
    "Please give us a simple answer, so that we don't have to think, because if we think, we might find answers that don't fit the way we want the world to be."
    ~ Terry Pratchett in Nation

    eBookworm.us

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles