上传时重命名文件

时间:2017-06-09 19:57:36

标签: php html upload

我有这个上传脚本来上传多个文件,工作正常。但是我想将上传的文件重命名为页面中设置的变量加上随机数

if(isset($_FILES['files'])){
    $errors= array();
    foreach($_FILES['files']['tmp_name'] as $key => $tmp_name ){
        $file_name = $key.$_FILES['files']['name'][$key];
        $file_size =$_FILES['files']['size'][$key];
        $file_tmp =$_FILES['files']['tmp_name'][$key];
        $file_type=$_FILES['files']['type'][$key];  
        $desired_dir="hr-documents";
        if(empty($errors)==true){
            if(is_dir($desired_dir)==false){
                mkdir("$desired_dir", 0700);        // Create directory if it does not exist
            }
            if(is_dir("$desired_dir/".$file_name)==false){
                move_uploaded_file($file_tmp,"$desired_dir/".$file_name);
            }else{                                  // rename the file if another one exist
                $new_dir="$desired_dir/".$file_name.time();
                 rename($file_tmp,$new_dir) ;               
            }
         mysql_query($query);           
        }else{
                print_r($errors);
        }
    }
    if(empty($error)){
        echo"There has been an error.";}

有办法做到这一点吗?

2 个答案:

答案 0 :(得分:1)

试试这个

$date = date("dmY");
$newfilename = round(microtime(true)) . '.' . end($temp);
move_uploaded_file($_FILES["passport"]["tmp_name"], "$desired_dir/image_" . $date . "_" . $newfilename);

这会创建一个新文件名,例如 image_09210313_32134144.jpg

答案 1 :(得分:0)

    $length = 10;
    $randomString = substr(str_shuffle("123456789abcdefijknopqrstuvwxyzABCHIJKOPQRSTUVWXYZ"), 0, $length);

    $newfilename = "$variable-randomString";

     move_uploaded_file($file_tmp,"$desired_dir/".$newfilename);