使用随机文件名上传多个图像

时间:2014-02-18 03:33:31

标签: php

现在,所有图片都使用文件名上传,但我想将文件名更改为随机名称(以避免带符号的名称)但是当我尝试这样做时,如果我上传了多个图片,它们将与最后选择的文件的图像相同。

<input type='file' name='file[]'>

条件:

 $allowed = array('jpg', 'JPG', 'jpeg', 'png', 'bmp', 'tiff', 'gif');
        $max_file_size = 2048*1000;
        $path = "images/images/"; // Upload directory
        $count = 0;
        if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST"){
            if ($_FILES['file']['name'] != "") {
                foreach ($_FILES['file']['name'] as $f => $name) {     
                    if ($_FILES['file']['error'][$f] == 4) {
                        continue;
                    }          
                    if ($_FILES['file']['error'][$f] == 0) {               
                        if ($_FILES['file']['size'][$f] > $max_file_size) {
                            $errors[] = "$name is too large!";
                            continue; 
                        }
                        else if( ! in_array(pathinfo($name, PATHINFO_EXTENSION), $allowed) ){
                            $errors[] = "$name is not a valid format";
                            continue; 
                        }
                        else{ 
                            if(move_uploaded_file($_FILES["file"]["tmp_name"][$f], $path.$name))
                            $images = array(
                                'images'    => $path.$name,
                                'ad_id'     => $_POST['id']
                                ); 
                                add_images($images);    
                            $count++; 
                        }
                    }
                }
            }
        }

1 个答案:

答案 0 :(得分:2)

您可以将索引添加到图像名称之前。尝试改变

if(move_uploaded_file($_FILES["file"]["tmp_name"][$f], $path.$name))

if(move_uploaded_file($_FILES["file"]["tmp_name"][$f], $path.$f.$name))

'images' => $path.$name,

的原理相同