Skip to content
Advertisement

Renaming files with random string after upload and storing the name in array

I’m trying to process multiple files upload with foreach then rename the files with random string and store the file names in an array, here’s my current code:

    // 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)) {

                }
            }    
        }
    }

I can’t find where the problem is, should I use foreach for every generated file name then use move_uploaded_file inside the foreach?

Advertisement

Answer

You are completely wrong. You have initialized $_FILES['files']['name'] in the foreach statement and trying to access $_FILES['files']['error'] and $_FILES["files"]["tmp_name"] in each iteration. Since this is an array it not possible.

So solution is as follows,

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])) {

            }
        }    
    }
}

Hope this can help you.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement