在php mysql中上传时重命名文件

I have a simple piece of code for uploading the files in php/mysql and it works well.

$target = "uploads/clients/";
  $target = $target . basename( $_FILES['photo']['name']);

  $pic=($_FILES['photo']['name']);

  //Writes the photo to the server
  if(move_uploaded_file($_FILES['photo']['tmp_name'], $target))
  {
  $insertSQL = sprintf("INSERT INTO clients (img, `cname`) VALUES (%s, %s)",
                       GetSQLValueString($pic, "text"),
                       GetSQLValueString($_POST['cname'], "text"));

  mysql_select_db($database_thebest, $thebest);
  $Result1 = mysql_query($insertSQL, $thebest) or die(mysql_error());

Now what I want is to rename the filename if that filename already exists and then insert the renamed filename to the database

Thanks for your reply

Try this...

$upload_dir = "uploads/clients/";
$target = $upload_dir . basename( $_FILES['photo']['name']);
while(file_exists($target)){
    $new = time().rand();
    $target = $upload_dir . '_' . $new . '_' . basename( $_FILES['photo']['name']);
}

// rest of the code now...
$pic= $new . ($_FILES['photo']['name']);

Run a SELECT query checking to see if the name exists. If it does not, INSERT it. So, select all from your table where the name = your file name. If numrows > 0 you change the name.

Actually why don't you just use the auto increment value as the name and store whatever you want to call it in a separate column. Then you'll know each name will be different and you won't have crazy long urls or file names.

First you must check table, that filename already exists or not.

select * from client where cname="filename";

if filename exist, you can must change filename .

You can do it by many ways.

Method 1

Check file_exists() before save to the server :

if (file_exists("../img/imageDirectory/" . $_FILES["file"]["name"]))
{
   echo $_FILES["file"]["name"] . " already exists. ";
}
else
{
   move_uploaded_file($_FILES["file"]["tmp_name"], "../img/imageDirectory/" . $_FILES["file"]["name"]);
  // Others insert statements here...
}

Method 2

Use microtime() to generate unique name for each file :

$temp = explode(".",$_FILES["file"]["name"]);
$newfilename = substr(microtime(), 2, 7) . '.' .end($temp);
move_uploaded_file($_FILES["file"]["tmp_name"], "../img/imageDirectory/" . $newfilename;

mysql_* functions are deprecated. Do not use them any more.

Try to use PDO or mysqli.