Jump to content

File Handling: Changing file names on the fly


Guardian-Mage

Recommended Posts

I have this basic file upload script:

<?php
if (($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/pjpeg")
&& ($_FILES["file"]["size"] < 20000))
  {
  if ($_FILES["file"]["error"] > 0)
    {
    echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
    }
  else
    {
    echo "Upload: " . $_FILES["file"]["name"] . "<br />";
    echo "Type: " . $_FILES["file"]["type"] . "<br />";
    echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
    echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />";

    if (file_exists("upload/" . $_FILES["file"]["name"]))
      {
      echo $_FILES["file"]["name"] . " already exists. ";
      }
    else
      {
      move_uploaded_file($_FILES["file"]["tmp_name"],
      "upload/" . $_FILES["file"]["name"]);
      echo "Stored in: " . "upload/" . $_FILES["file"]["name"] . "<br />
  <img scr=\"upload/" . $_FILES["file"]["name"] . "\" alt=\"Hello World\" />" ;
      }
    }
  }
else
  {
  echo "Invalid file";
  }
?>

 

I need to have my script rename the file if it already exists, like add a number to it until it is ok. How do i do this?

Link to comment
Share on other sites

You can try creating a function that gets called if the file exists.  The function would then use the rand function to append a random number on the end of the file name.

 

The function would look something like this:

 

function randomName()

{

    $randNum = rand(1,100000); // returns random number between 1 and 100,000

    $_FILES["file"]["name"] = $_FILES["file"]["name"].$randNum;

    return $_FILES["file"]["name"];

    Go();

}

 

Ofcourse you would have to put your existing code into a function, so in the end it would look something like this:

 

function Go ($uploadFile)

{

// your existing code in here

 

// if file exists then call randomFile()

}

 

Not sure if that will work and none of that code has been tested, but give it a shot.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.