重命名上传的文件有些错误?

时间:2017-01-12 17:45:25

标签: php

以下是我用于将文件上传到目录的代码。它工作正常。我的主要问题是:

我试过这样做:

function get_unique_filename($name) { 
   $imgExt = strtolower(pathinfo($name,PATHINFO_EXTENSION)); 
   $date = new DateTime();
   $date= $date->getTimestamp();
   $newname ="bogen_". substr(hash('ripemd160',$date),0,12) .".".$imgExt;  
   return $newname;
}

function upload(){ 
    $valid_formats = array("jpg", "png"); 

    $max_file_size = 1024*3000;  

    $path = "../uploads/images/";

    $count = 0;


    if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST"){

        foreach ($_FILES['files']['name'] as $f => $name){ 
            if ($_FILES['files']['error'][$f] == 4) {
                continue;  
            } 
            if ($_FILES['files']['error'][$f] == 0) {           
                if ($_FILES['files']['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; // Skip invalid file formats
                }

                // No error found! Move uploaded files 
                else{  
 if(move_uploaded_file($_FILES["files"]["tmp_name"][$f], $path.$this->get_unique_filename($name))){
                        $count++; // Number of successfully uploaded file

                        // save name to database
                        $this->name = $newname;

                        if($this->create()){
                            // successfully added to databaes
                        }
                    }
                }
            }
        }
    }
}

上传多个文件时,我将获得相同的文件名和文件...如何修复它: same file name

2 个答案:

答案 0 :(得分:1)

Foo

中的

+ add:explicit Foo(int a):bar(a){}

get_unique_filename($name)

答案 1 :(得分:1)

您必须检查文件是否存在同名,如果存在,则必须重命名该文件。

function get_unique_filename($name) { 
   $imgExt = strtolower(pathinfo($name,PATHINFO_EXTENSION)); 
   $date = new DateTime();
   $date = $date->getTimestamp();
   $dir = "../uploads/images/";
   $i = 0;
   do {
       $newname ="bogen_". substr(hash('ripemd160',$date),0,12);  
       $image_name = $newname . ($i > 0 ? "_($i)" : "") . "." . $imgExt;
       $i++;
       $path = $dir . $image_name;
   } while(file_exists($path));
   return $newname;
}