KPO
KPO

Reputation: 880

How to rename a file if the name already exists?

I am using the following script. it basically checks if the name of the file being uploaded already exists, if it does it should rename it to something else and upload it. So far it doesn't work. either it renames all files or when i try to open the file via webpage it says corrupt file.

Code:

$sql="SELECT filename FROM doc_u WHERE person_id= '$pid'";  

    $result=mysql_query($sql);

    $query = mysql_query($sql) or die ("Error: ".mysql_error());

 if ($result == "")
 {
 echo "";
  }
   echo "";


    $rows = mysql_num_rows($result);

    if($rows == 0)
    {
   print("");

    }
    elseif($rows > 0)
    {
   while($row = mysql_fetch_array($query))
    {

   $existing = $row['filename'];

   print("");
   }

   }

     if ( $filename === $existing ) {
$filename = $uniqueidgenerator.strrchr($_FILES['filename']['name'], ".");

    } else {
     $filename = $_FILES['filename']['name'];;
    }

//After checking it will move the files

      if(move_uploaded_file($_FILES['filename']['tmp_name'],$upload_path . $filename))
     echo ''; 
  else
     echo ''; 

Upvotes: 1

Views: 1622

Answers (2)

Jason Clawson
Jason Clawson

Reputation: 1027

There isn't much code to go on here. I suspect that $filename isn't initialized properly. So in your if ( $filename === $existing ) that is really saying if(undefined === undefined) which would always be true.

I don't see why the files would be corrupted. That could be a different issue entirely.

Also, watch out for your sql statement there. That is an SQL injection waiting to happen. It would be a lot better if you used prepared statements or at the very least use mysql_escape_string. This has been deprecated of course in favor of prepared statements.

A better workflow would be to insert a row in the db first with the file's meta data then rename the file using the primary key you got back. It is guaranteed to be unique always.

Upvotes: 1

Marc B
Marc B

Reputation: 360672

Given you're using a database already, let me say it asplainly as possible: NEVER USE A USER-PROVIDED FILENAME. Instead, store each uploaded file by its corresponding DB record's primary key ID number (you are using auto-incrementing integers for ids, right?). Store the file's name in the database, and now you can have as many "text.txt" files as you want, because each actual file will be named "1", "53", and "207", etc...

Upvotes: 2

Related Questions