【问题标题】:Renaming files with random string after upload and storing the name in array上传后用随机字符串重命名文件并将名称存储在数组中
【发布时间】:2018-07-01 12:11:34
【问题描述】:

我正在尝试使用foreach 处理多个文件上传,然后用随机字符串重命名文件并将文件名存储在一个数组中,这是我当前的代码:

    // this variable stores the id of last inserted row in MySQLi DB
    $last_shipment_id = mysqli_insert_id($con);
    // Array of valid file formats
    $valid_formats = array("jpg", "jpeg", "png");
    // the upload path
    $path = "../uploads/"; // Upload directory
    // count variable for foreach counting
    $count = 0;
    // variable for generated file names to use them later
    $new_file_name = array();


    foreach ($_FILES['files']['name'] as $f => $name) {
        $ext = pathinfo($name, PATHINFO_EXTENSION);
        $new_file_name[] = randomNumber(14)."-".$last_shipment_id.'.'.$ext;

        if ($_FILES['files']['error'][$f] == 4) {
            continue;
        }          
        if ($_FILES['files']['error'][$f] == 0) {              
            if( ! in_array(pathinfo($name, PATHINFO_EXTENSION), $valid_formats) ){
                $message[] = "$name is not a valid format";
                continue;
            } else {
                if(move_uploaded_file($_FILES["files"]["tmp_name"][$f], $path.$new_file_name)) {

                }
            }    
        }
    }

我找不到问题出在哪里,是否应该为每个生成的文件名使用foreach,然后在foreach 中使用move_uploaded_file

【问题讨论】:

    标签: php file-upload multifile-uploader


    【解决方案1】:

    你完全错了。您已在 foreach 语句中初始化 $_FILES['files']['name'] 并尝试在每次迭代中访问 $_FILES['files']['error']$_FILES["files"]["tmp_name"]。由于这是一个数组,所以不可能。

    所以解决方法如下,

    foreach($_FILES as $key=>$row){
       $ext = pathinfo($row[$key]['files']['name'], PATHINFO_EXTENSION);
       $new_file = randomNumber(14)."-".$last_shipment_id.'.'.$ext;
        array_push($new_file_name,$new_file);
        if ($row[$key]['files']['error'] == 4) {
            continue;
        }          
        if ($row[$key]['files']['error'] == 0) {              
            if( ! in_array($ext,  $valid_formats) ){
               $error_msg = "The file ". $new_file. " is not a valid format";
               array_push($message, $error_msg); 
                continue;
            } else {
                if(move_uploaded_file($row[$key]["files"]["tmp_name"], $path.$new_file_name[$key])) {
    
                }
            }    
        }
    }
    

    希望对你有帮助。

    【讨论】:

      猜你喜欢
      • 2017-05-29
      • 1970-01-01
      • 2013-07-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多