-2

如果已经上传了同名文件,我需要编写代码以重命名文件。例如,如果您上传“internet.jpg”,但该文件已经存在于服务器端和bd,则系统重命名为“internet_2.jpg”

我的代码:

    <?php

mysql_connect("localhost", "user", "user") or die(mysql_error()) ;
mysql_select_db("view") or die(mysql_error()) ;

if ($_FILES["imagen"]["error"] > 0){
  echo "ha ocurrido un error";
} else {

  $permitidos = array("image/jpg", "image/jpeg", "image/gif", "image/png");
  $limite_kb = 100;

  if (in_array($_FILES['imagen']['type'], $permitidos) && $_FILES['imagen']['size'] <= $limite_kb * 1024){

    $ruta = "./image/" . $_FILES['imagen']['name'];

      $resultado = @move_uploaded_file($_FILES["imagen"]["tmp_name"], $ruta);   
      if ($resultado){
        $nombre = $_FILES['imagen']['name'];

        @mysql_query("UPDATE product SET  image='data/$nombre' Where id=55")  ;

        echo "la imagen ha sido actualizada exitosamente";
        echo "

    ";
      } else {
        echo "ocurrio un error al mover el archivo.";
      }

  } else {
    echo "archivo no permitido, es tipo de archivo prohibido o excede el tamano de $limite_kb Kilobytes";
  }
}

?>

- - - - - - - - - - - 谢谢 - - - - - - - - - - - - - - --

thank you very much Farhan Ihsas, your code worked perfect!
 I just change two lines

$new_name =     $rand . '_'.   $dotName ;

and

@mysql_query("UPDATE product SET  image='./image/$new_name' Where product_id=55")  ;


Thanks for such a quick response!

thank you both ( Farhan Ihsas and Kieran ) 
4

2 回答 2

0

您想使用file_existsmove_uploaded_file的组合

例如

function setFilename($file, $count = 1) {
   if (file_exists($file)) {
       return setFilename($file, $count++);
   } else {
       $path_parts = pathinfo($file);
       move_uploaded_file($file, "{$fileData['dirname']}/{$path_parts['filename']}_{$count}.{$path_parts['extension']}";  
   }
}
于 2013-08-18T16:49:53.553 回答
0

我假设您的代码没有任何错误,因此找出该行并替换它..

if(in_array($_FILES['imagen']['type'],$permitidos) && $_FILES['imagen']['size'] <=$limite_kb * 1024){

$fileName = $_FILES['imagen']['name'];
$ruta = "./image/" . $fileName ;
if (file_exists($ruta)) {

$dotType = pathinfo( $fileName, PATHINFO_FILENAME);
$rand = rand(111, 2333);
$dotName = str_replace('.' . $dotType, '', $fileName) ;
$new_name = $dotName . '_' .  $rand . '.'.  $dotType ;

$ruta = "./image/" . $new_name;
} 
$resultado = @move_uploaded_file($_FILES["imagen"]["tmp_name"], $ruta);    
于 2013-08-18T17:42:26.240 回答