我需要复制,然后重命名文件的副本,如果它已经存在

时间:2013-07-24 17:54:07

标签: php file-upload filenames file-rename

需要复制并重命名文件的副本(如果已存在)

$pastaTemp = $_FILES['imagem_principal']['tmp_name'];
$pastaUpload = $_SERVER['DOCUMENT_ROOT']."/casaunica/imagens/acabamentos/";
$arquivo = $pastaUpload . $_FILES['imagem_principal']['name']; //filename.jpg

if(!file_exists($pastaUpload. $_FILES['imagem_principal']['name'])){
      $arquivo = $pastaUpload . $_FILES['imagem_principal']['name'];
} else {
    $nome_arquivo = explode(".",$_FILES['imagem_principal']['name']);
       do {
          $para = $nome_arquivo[0]."_".$i.".".$nome_arquivo[1];
          $nome_novo = rename($arquivo, $pastaUpload . $para);
          $arquivo = $pastaUpload .$nome_novo;
          $i++; 
       } while(file_exists($pastaUpload.$_FILES['imagem_principal']['name']));
}

输出:filename.jpg_1

应该是:filename_2.jpg

它无法替换旧文件..这就是我需要用数字重命名的原因 它不需要在循环中进行,但每次上传文件时都需要进行

1 个答案:

答案 0 :(得分:1)

试试这段代码,让我知道它是否有效

<强>功能

<?php
  function recursive_naming( $file, $i = 1 ) {
    $dirname    = dirname( $file ).DIRECTORY_SEPARATOR;
    $filename   = pathinfo( $file, PATHINFO_FILENAME );
    $extension  = pathinfo( $file, PATHINFO_EXTENSION );

    if ( !file_exists( $file ) ) {
      return $file;
    }
    $filename = preg_replace( '/_\d+$/', '', $filename );
    $file = $dirname.$filename."_".$i.".".$extension;
    $i++;
    return recursive_naming( $file, $i );
  }
?>

示例:

<?php
  $pastaTemp    = $_FILES['imagem_principal']['tmp_name'];
  $pastaUpload  = $_SERVER['DOCUMENT_ROOT']."/casaunica/imagens/acabamentos/";
  $arquivo      = recursive_naming( $pastaUpload.$_FILES['imagem_principal']['name'] );
?>

如果filename_2.jpg存在,则会输出filename.jpg;如果filename_3.jpg也存在,则输出filename_2.jpg,依此类推......