【问题标题】:Rename a file if already exists -php file upload重命名文件(如果已存在)-php 文件上传
【发布时间】:2017-02-20 20:49:57
【问题描述】:

如果已存在,我想重命名已上传的文件。如果已经存在,我想将其重命名为 img1.jpg、img2.jpg。我尝试了很多例子,但没有适合下面的代码:

<?php
$valid_formats = array(
    "jpg",
    "png",
    "gif",
    "zip",
    "bmp",
    "pdf",
    "docx",
    "PDF",
    "xlxc"
);
$max_file_size = 3024;
$path          = "images/"; // Upload directory
$count         = 0;

if (isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST") {
    $fname = $_FILES['attach']['name'];
    foreach ($_FILES['attach']['name'] as $f => $name) {
        if ($_FILES['attach']['error'][$f] == 4) {
            continue;
        }
        
        if ($_FILES['attach']['error'][$f] == 0) {
            if ($_FILES['attach']['size'][$f] > $max_file_size) {
                $message[] = "$name is too large!.";
                continue;
            }
            
            elseif (!in_array(pathinfo($name, PATHINFO_EXTENSION), $valid_formats)) {
                $message[] = "$name is not a valid format";
                continue;
            }
            
            else {
                if (move_uploaded_file($_FILES["attach"]["tmp_name"][$f], $path . $name))
                    $count++;
                
            }
        }
    }
    
}
?>

需要对上述代码中存在的文件进行一些更新。

【问题讨论】:

  • 那么您的问题到底是什么?我们不喜欢“为我做作业”式的问题。你有任何错误吗?什么有效,什么无效?您的代码 sn-p 包含大量验证等,您的问题也可以省略。
  • 使用file_exists检查文件或目录是否存在
  • 你为什么要使用重命名...请时间喜欢的东西不要覆盖原来的
  • @ Damien Overeem 我尽我所能尝试了一切……我没有要求做作业

标签: php file-upload file-exists


【解决方案1】:

你可以试试替换

else{  
    if(move_uploaded_file( $_FILES["attach"]["tmp_name"][$f], $path.$name ))
    $count++; 

}

else {

    $targetfile = $path . $name;

    if( file_exists( $targetfile ) ){

        /* get filename & extension from target file */
        $filename=pathinfo( $targetfile, PATHINFO_FILENAME );
        $extension=pathinfo( $targetfile, PATHINFO_EXTENSION );

        /* if the last character of the file's name is a digit, increment by one */
        $lastchar = intval( substr( $filename, strlen( $filename )-1 ) );

        if( $lastchar && !is_nan( $lastchar ) ) {
            /* Get the actual integer value from the end of the filename */
            preg_match( '@\d+$@', $filename, $matches );
            if( !empty( $matches ) ) $lastchar=$matches[0];

            /* Remove original number and replace with new incremented value */
            $filename = substr( $filename, 0, strlen( $filename ) - strlen( $lastchar ) ) . ( $lastchar + 1 );

        } else {
            /* last character was not a digit, add '1' to filename */
            $filename.='1';
        }

        /* determine new file's path */
        $targetfile = $path . $filename . '.' . $extension;

        clearstatcache();
    }

    if( move_uploaded_file( $_FILES["attach"]["tmp_name"][$f], $targetfile ) ) $count++;
}

它应该确定文件是否已经存在于指定的目标文件夹中 - 如果它存在并且有一个整数作为其名称的最后一部分,它应该将该值加一并创建一个新的文件名。如果没有整数,它应该简单地添加 '1' - 但如果文件不存在,它将使用原始名称。

【讨论】:

    【解决方案2】:

    试试这个:

    before moving the file to server put this check
    
    $fname = $_FILES['attach']['name'];
    if(file_exist($path))
    {
        $file = explode($fname);    // explode file name and extension
    
        $rand = rand(1, 100);
        $fname = $file[0].'.'.$rand.$file[1];   // combine file name with some random value with extension
    }
    
    // Now fname will contain the original name or modifed name in it
    // You can maintain a counter instead of random value that gives you 1,2,3 ...
    

    【讨论】:

      猜你喜欢
      • 2013-09-29
      • 1970-01-01
      • 2014-07-20
      • 2015-03-18
      • 2014-08-09
      • 2021-10-25
      • 2020-09-17
      • 2015-06-14
      相关资源
      最近更新 更多