What are common pitfalls when using a foreach loop to move uploaded files to a directory in PHP?

Common pitfalls when using a foreach loop to move uploaded files to a directory in PHP include not checking if the file was successfully uploaded, not handling errors properly, and not ensuring the destination directory exists before moving the files. To solve these issues, you should check if the file was uploaded successfully, handle any errors that may occur during the file moving process, and create the destination directory if it does not exist.

// Check if files were uploaded successfully and move them to a directory
if(isset($_FILES['file']['name'])){
    $uploadDir = 'uploads/';

    // Create the directory if it does not exist
    if (!file_exists($uploadDir)) {
        mkdir($uploadDir, 0777, true);
    }

    foreach($_FILES['file']['tmp_name'] as $key => $tmp_name){
        $file_name = $_FILES['file']['name'][$key];
        
        if(move_uploaded_file($tmp_name, $uploadDir . $file_name)){
            echo "File uploaded successfully: " . $file_name . "<br>";
        } else {
            echo "Error moving file: " . $file_name . "<br>";
        }
    }
}